Spaces:
Sleeping

BaseAdmin / server.js
guisousa's picture
Create server.js
2a2658a verified
Raw History Blame Contribute Delete
5.24 kB
import express from "express";
import cors from "cors";
import multer from "multer";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import crypto from "crypto";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 7860;
/* ========= CORS ========= */
const allow = [
process.env.CLIENT_ORIGIN,
process.env.ADMIN_ORIGIN,
].filter(Boolean);
app.use(cors({
origin: (origin, cb) => {
if (!origin) return cb(null, true); // ferramentas, curl, etc.
if (allow.length === 0 || allow.includes(origin)) return cb(null, true);
return cb(new Error(`Origem não permitida: ${origin}`));
},
credentials: true
}));
app.use(express.json({ limit: "10mb" }));
/* ========= Storage simples (arquivos JSON) ========= */
const DATA_DIR = path.join(__dirname, "data");
const UPLOAD_DIR = path.join(__dirname, "uploads");
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR, { recursive: true });
function fileOf(name) { return path.join(DATA_DIR, `${name}.json`); }
function readList(name) {
const f = fileOf(name);
if (!fs.existsSync(f)) return [];
try { return JSON.parse(fs.readFileSync(f, "utf-8")); }
catch { return []; }
}
function writeList(name, arr) {
fs.writeFileSync(fileOf(name), JSON.stringify(arr, null, 2));
}
function genId() { return crypto.randomUUID(); }
function nowISO() { return new Date().toISOString(); }
function applyOrdering(list, ordering) {
if (!ordering) return list;
const desc = ordering.startsWith("-");
const key = desc ? ordering.slice(1) : ordering;
return [...list].sort((a, b) => {
const av = a[key], bv = b[key];
if (av == null && bv == null) return 0;
if (av == null) return desc ? 1 : -1;
if (bv == null) return desc ? -1 : 1;
if (av < bv) return desc ? 1 : -1;
if (av > bv) return desc ? -1 : 1;
return 0;
});
}
function filterExact(list, query) {
// filtros exatos ?campo=valor (ignora "ordering")
const entries = Object.entries(query || {}).filter(([k]) => k !== "ordering");
if (!entries.length) return list;
return list.filter(item =>
entries.every(([k, v]) => String(item?.[k]) === String(v))
);
}
/* ========= Upload ========= */
const storage = multer.diskStorage({
destination: (_, __, cb) => cb(null, UPLOAD_DIR),
filename: (_, file, cb) => {
const ext = path.extname(file.originalname) || "";
const base = path.basename(file.originalname, ext).replace(/[^\w.-]+/g, "_");
cb(null, `${Date.now()}_${base}${ext}`);
}
});
const upload = multer({ storage });
app.use("/uploads", express.static(UPLOAD_DIR));
app.post("/upload", upload.single("file"), (req, res) => {
if (!req.file) return res.status(400).json({ error: "file obrigatório" });
const file_url = `${req.protocol}://${req.get("host")}/uploads/${req.file.filename}`;
res.json({ file_url });
});
/* ========= Auth (mock simples; plugue JWT aqui se quiser) ========= */
app.get("/auth/me", (req, res) => {
// Ex.: validar Authorization: Bearer <token> com process.env.JWT_SECRET
res.json({ role: "admin", email: "admin@example.com", name: "Admin" });
});
/* ========= Factory CRUD ========= */
function mountCrud(resource) {
// GET /resource
app.get(`/${resource}`, (req, res) => {
let rows = readList(resource);
rows = filterExact(rows, req.query);
rows = applyOrdering(rows, req.query.ordering);
res.json(rows);
});
// POST /resource
app.post(`/${resource}`, (req, res) => {
const rows = readList(resource);
const item = req.body || {};
if (!item.id) item.id = genId();
if (!item.created_at) item.created_at = nowISO();
rows.push(item);
writeList(resource, rows);
res.status(201).json(item);
});
// PUT /resource/:id
app.put(`/${resource}/:id`, (req, res) => {
const rows = readList(resource);
const { id } = req.params;
const i = rows.findIndex(r => String(r.id) === String(id));
if (i < 0) return res.status(404).json({ error: "not found" });
rows[i] = { ...rows[i], ...req.body, id };
writeList(resource, rows);
res.json(rows[i]);
});
// DELETE /resource/:id
app.delete(`/${resource}/:id`, (req, res) => {
const rows = readList(resource);
const next = rows.filter(r => String(r.id) !== String(req.params.id));
writeList(resource, next);
res.json({ ok: true });
});
// GET /resource/filter → { data: [...] } (compat com seu AdminAgendamentos)
app.get(`/${resource}/filter`, (req, res) => {
let rows = readList(resource);
rows = filterExact(rows, req.query);
rows = applyOrdering(rows, req.query.ordering);
res.json({ data: rows });
});
}
/* ========= Registra seus 5 recursos ========= */
[
"agendamentos", // API agendamento
"barbeiros", // API barbeiro
"produtos", // API produto
"servicos", // API serviço
"vendas" // API venda
].forEach(mountCrud);
/* ========= Saúde ========= */
app.get("/", (_, res) => res.send("OK - BaseBarber API"));
app.listen(PORT, () => console.log(`API rodando na porta ${PORT}`));