crud-api-express
v1.1.1
Published
npm install crud-api-express
Downloads
13
Maintainers
Readme
CRUD API Controller using Express and Mongoose
npm 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.
Table of Contents
Introduction
The CrudController
class is designed to simplify the creation of RESTful APIs in Node.js applications that use MongoDB as the database backend. It abstracts away common CRUD operations, error handling, middleware integration, and supports custom routes and aggregation pipelines.
Installation
To use CrudController
in your Node.js project, follow these steps:
- Install Node.js: Make sure you have Node.js installed on your system.
- Install Dependencies: Navigate to your project directory and run:
npm install express mongoose
Usage
Here's a basic example of how to use CrudController:
import express from 'express'; import mongoose from 'mongoose'; import CrudController from 'crud-api-express';
const Schema = mongoose.Schema; const ExampleSchema = new Schema({ type: { type: String, default: 'Percentage', enum: ['Percentage', 'Flat'] }, status: { type: String, default: 'Active', trim: true }, expiry_date: { type: Date, index: true, trim: true }, }, { timestamps: true, versionKey: false });
const ExampleModel = mongoose.model('Example', ExampleSchema);
const options = {
middleware: [
(req, res, next) => {
// Example: Authentication middleware
const authToken = req.headers.authorization;
if (!authToken) {
return res.status(401).json({ message: 'Unauthorized' });
}
// Verify token logic here
next();
},
(req, res, next) => {
// Example: Logging middleware
console.log(Request received at ${new Date()}
);
next();
}
],
onSuccess: (res, method, result) => {
console.log(Successful ${method} operation:
, result);
res.status(200).json({ success: true, data: result });
},
onError: (res, method, error) => {
console.error(Error in ${method} operation:
, error);
res.status(500).json({ error: error.message });
},
methods: ['GET', 'POST', 'PUT', 'DELETE'],
relatedModel: RelatedModel,
relatedField: 'relatedId',
aggregatePipeline: [
{ $match: { status: 'Active' } },
{ $sort: { createdAt: -1 } }
],
customRoutes: [
{
method: 'get',
path: '/custom-route',
handler: (req, res) => {
res.json({ message: 'Custom route handler executed' });
}
},
{
method: 'post',
path: '/custom-action',
handler: (req, res) => {
// Custom logic for handling POST request
res.json({ message: 'Custom action executed' });
}
}
]
};
const exampleController = new CrudController(ExampleModel, 'examples', options);
const mongoURI = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Connected to MongoDB');
const app = express();
app.use(express.json());
app.use('/api', exampleController.getRouter());
console.log(exampleController.getRoutes());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
}) .catch(err => { console.error('Error connecting to MongoDB:', err.message); process.exit(1); });
API
model: Mongoose model for CRUD operations. endpoint: API endpoint path. options: Optional configuration for CRUD operations. Methods getRouter(): Router - Returns the Express Router instance configured with CRUD routes.
CrudOptions Configuration options for CrudController.
options
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 - 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 routes definitions.