UNPKG

maggie-api

Version:

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

48 lines (47 loc) 2.34 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.insertMany = exports.getById = exports.getAll = exports.deleteById = exports.updateDoc = exports.createDoc = void 0; const createDoc = (model, data) => __awaiter(void 0, void 0, void 0, function* () { return yield model.create(data); }); exports.createDoc = createDoc; const updateDoc = (model, data) => __awaiter(void 0, void 0, void 0, function* () { if (!data._id) throw new Error("Missing _id for update"); return yield model.findByIdAndUpdate(data._id, data, { new: true }); }); exports.updateDoc = updateDoc; const deleteById = (model, id) => __awaiter(void 0, void 0, void 0, function* () { return yield model.findByIdAndDelete(id); }); exports.deleteById = deleteById; const getAll = (model, settings) => __awaiter(void 0, void 0, void 0, function* () { return settings.getKeys.length ? yield model.find().select(settings.getKeys.join(" ")) : yield model.find(); }); exports.getAll = getAll; const getById = (model, id, settings) => __awaiter(void 0, void 0, void 0, function* () { var _a; return ((_a = settings.getByIdKeys) === null || _a === void 0 ? void 0 : _a.length) ? yield model.findById(id).select(settings.getByIdKeys.join(" ")) : yield model.findById(id); }); exports.getById = getById; // 🔹 insertMany service const insertMany = (model, docs) => __awaiter(void 0, void 0, void 0, function* () { if (!Array.isArray(docs)) { throw new Error("insertMany expects an array of documents"); } return yield model.insertMany(docs); }); exports.insertMany = insertMany;