UNPKG

maggie-api

Version:

🧙‍♀️ A magical Express middleware to auto-generate CRUD APIs for Mongoose models with validation, unique keys, and middlewares.

34 lines (33 loc) 2.1 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = require("express"); const controllers_1 = require("../controllers"); const validateBody_1 = require("../utils/validateBody"); const joi_1 = __importDefault(require("joi")); const createMaggie = ({ prefix, models }) => { const router = (0, express_1.Router)(); models.forEach(({ model, path, validationSchema, primaryKey, middleWares = [], getKeys = [], getByIdKeys = [], settings, }) => { var _a, _b, _c, _d; const settingsObj = Object.assign({ getByIdKeys: (_b = (_a = settings === null || settings === void 0 ? void 0 : settings.getById) === null || _a === void 0 ? void 0 : _a.keys) !== null && _b !== void 0 ? _b : getByIdKeys, getKeys: (_d = (_c = settings === null || settings === void 0 ? void 0 : settings.get) === null || _c === void 0 ? void 0 : _c.keys) !== null && _d !== void 0 ? _d : getKeys, primaryKey }, settings); const controller = (0, controllers_1.createController)(model, settingsObj); const subRouter = (0, express_1.Router)(); const middlewareStack = [...middleWares]; const bulkMiddlewareStack = [...middleWares]; if (validationSchema) { middlewareStack.push((0, validateBody_1.validateBody)(validationSchema)); const bulkValidationSchema = joi_1.default.array().items(validationSchema); bulkMiddlewareStack.push((0, validateBody_1.validateBody)(bulkValidationSchema)); } subRouter.post("/", ...middlewareStack, controller.addOrUpdate); subRouter.post("/bulk", ...bulkMiddlewareStack, controller.insertMany); subRouter.delete("/:id", ...middleWares, controller.remove); subRouter.get("/", ...middleWares, controller.getAll); subRouter.get("/:id", ...middleWares, controller.getById); router.use(`${prefix}/${path}`, subRouter); }); return router; }; exports.default = createMaggie;