Gathering detailed insights and metrics for crud-api-express
Gathering detailed insights and metrics for crud-api-express
Gathering detailed insights and metrics for crud-api-express
Gathering detailed insights and metrics for crud-api-express
npm install crud-api-express
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
4
Install the package using npm:
1npm install crud-api-express
This project provides a flexible and reusable CRUD (Create, Read, Update, Delete) API controller for MongoDB using Express.js and Mongoose.
The CrudController
class simplifies the creation of RESTful APIs in Node.js applications using MongoDB. It abstracts away common CRUD operations, error handling, middleware integration, and supports custom routes and aggregation pipelines.
Here's a basic example of how to use in Es module CrudController
:
1import express from 'express'; 2import mongoose from 'mongoose'; 3import CrudController from 'crud-api-express'; 4 5const Schema = mongoose.Schema; 6const ExampleSchema = new Schema( 7 { 8 type: { type: String, default: 'Percentage', enum: ['Percentage', 'Flat'] }, 9 status: { type: String, default: 'Active', trim: true }, 10 expiry_date: { type: Date, index: true, trim: true }, 11 }, 12 { timestamps: true, versionKey: false } 13); 14 15const ExampleModel = mongoose.model('Example', ExampleSchema); 16 17const options = { 18 middleware: [ 19 (req, res, next) => { 20 const authToken = req.headers.authorization; 21 if (!authToken) { 22 return res.status(401).json({ message: 'Unauthorized' }); 23 } 24 next(); 25 }, 26 (req, res, next) => { 27 console.log(`Request received at ${new Date()}`); 28 next(); 29 }, 30 ], 31 onSuccess: (res, method, result) => { 32 console.log(`Successful ${method} operation:`, result); 33 res.status(200).json({ success: true, data: result }); 34 }, 35 onError: (res, method, error) => { 36 console.error(`Error in ${method} operation:`, error); 37 res.status(500).json({ error: error.message }); 38 }, 39 methods: ['GET', 'POST', 'PUT', 'DELETE'], 40 aggregatePipeline: [ 41 { $match: { status: 'Active' } }, 42 { $sort: { createdAt: -1 } }, 43 ], 44 customRoutes: [ 45 { 46 method: 'get', 47 path: '/custom-route', 48 handler: (req, res) => { 49 res.json({ message: 'Custom route handler executed' }); 50 }, 51 }, 52 { 53 method: 'post', 54 path: '/custom-action', 55 handler: (req, res) => { 56 res.json({ message: 'Custom action executed' }); 57 }, 58 }, 59 ], 60}; 61 62const exampleController = new CrudController(ExampleModel, 'examples', options); 63 64const mongoURI = 'mongodb://localhost:27017/mydatabase'; 65 66mongoose 67 .connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) 68 .then(() => { 69 console.log('Connected to MongoDB'); 70 71 const app = express(); 72 app.use(express.json()); 73 app.use('/api', exampleController.getRouter()); 74 75 console.log(exampleController.getRoutes()); 76 77 const PORT = process.env.PORT || 3000; 78 app.listen(PORT, () => { 79 console.log(`Server is running on port ${PORT}`); 80 }); 81 }) 82 .catch((err) => { 83 console.error('Error connecting to MongoDB:', err.message); 84 process.exit(1); 85 });
Here's a basic example of how to use in cjs module CrudController
:
1 2const express = require('express'); 3const mongoose = require('mongoose'); 4const CrudController = require('crud-api-express'); 5 6const Schema = mongoose.Schema; 7const ExampleSchema = new Schema( 8 { 9 type: { type: String, default: 'Percentage', enum: ['Percentage', 'Flat'] }, 10 status: { type: String, default: 'Active', trim: true }, 11 expiry_date: { type: Date, index: true, trim: true }, 12 }, 13 { timestamps: true, versionKey: false } 14); 15 16const ExampleModel = mongoose.model('Example', ExampleSchema); 17 18const options = { 19 middleware: [ 20 (req, res, next) => { 21 const authToken = req.headers.authorization; 22 if (!authToken) { 23 return res.status(401).json({ message: 'Unauthorized' }); 24 } 25 next(); 26 }, 27 (req, res, next) => { 28 console.log(`Request received at ${new Date()}`); 29 next(); 30 }, 31 ], 32 onSuccess: (res, method, result) => { 33 console.log(`Successful ${method} operation:`, result); 34 res.status(200).json({ success: true, data: result }); 35 }, 36 onError: (res, method, error) => { 37 console.error(`Error in ${method} operation:`, error); 38 res.status(500).json({ error: error.message }); 39 }, 40 methods: ['GET', 'POST', 'PUT', 'DELETE'], 41 aggregatePipeline: [ 42 { $match: { status: 'Active' } }, 43 { $sort: { createdAt: -1 } }, 44 ], 45 customRoutes: [ 46 { 47 method: 'get', 48 path: '/custom-route', 49 handler: (req, res) => { 50 res.json({ message: 'Custom route handler executed' }); 51 }, 52 }, 53 { 54 method: 'post', 55 path: '/custom-action', 56 handler: (req, res) => { 57 res.json({ message: 'Custom action executed' }); 58 }, 59 }, 60 ], 61}; 62 63const exampleController = new CrudController(ExampleModel, 'examples', options); 64 65const mongoURI = 'mongodb://localhost:27017/mydatabase'; 66 67mongoose 68 .connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) 69 .then(() => { 70 console.log('Connected to MongoDB'); 71 72 const app = express(); 73 app.use(express.json()); 74 app.use('/api', exampleController.getRouter()); 75 76 console.log(exampleController.getRoutes()); 77 78 const PORT = process.env.PORT || 3000; 79 app.listen(PORT, () => { 80 console.log(`Server is running on port ${PORT}`); 81 }); 82 }) 83 .catch((err) => { 84 console.error('Error connecting to MongoDB:', err.message); 85 process.exit(1); 86 });
getRouter(): Router
Returns the Express Router instance configured with CRUD routes.
1[ 2 { "method": "POST", "path": "/examples", "params": null }, 3 { "method": "GET", "path": "/examples", "params": ["filter", "sort", "page", "limit"] }, 4 { "method": "GET", "path": "/examples/:id", "params": ["id"] }, 5 { "method": "PUT", "path": "/examples/:id", "params": ["id"] }, 6 { "method": "DELETE", "path": "/examples", "params": ["filter"] }, 7 { "method": "DELETE", "path": "/examples/:id", "params": ["id"] }, 8 { "method": "GET", "path": "/examples/aggregate", "params": null }, 9 { "method": "GET", "path": "/examples/custom-route", "params": null }, 10 { "method": "POST", "path": "/examples/custom-action", "params": null } 11]
CrudOptions<T>
Option | Type | Description |
---|---|---|
middleware | ((req: Request, res: Response, next: NextFunction) => void)[] | Array of middleware functions |
onSuccess | (res: Response, method: string, result: T | T[]) => void | Success handler function |
onError | (res: Response, method: string, error: Error) => void | Error handler function |
methods | ('POST' | 'GET' | 'PUT' | 'DELETE')[] | Array of HTTP methods to support |
relatedModel | Model<any> | Related Mongoose model for relational operations |
relatedField | string | Field name for related models |
relatedMethods | ('POST' | 'GET' | 'PUT' | 'DELETE')[] | Methods to apply on related models |
aggregatePipeline | object[] | MongoDB aggregation pipeline stages |
customRoutes | { method: 'post' | 'get' | 'put' | 'delete', path: string, handler: (req: Request, res: Response) => void }[] | Array of custom route definitions |
🛠️ URL:
GET http://localhost:3000/api/examples?filter={"status":"Active"}&sort={"expiry_date":1}&page=1&limit=10
filter
→ Filter results (e.g., { "status": "Active" }
).sort
→ Sort order (e.g., { "expiry_date": 1 }
for ascending).page
→ Pagination (e.g., page=1
).limit
→ Number of results per page.This project is licensed under the ISC License.
If you find this package useful, consider supporting me:
Buy Me a Coffee ☕
No vulnerabilities found.
No security vulnerabilities found.