taughtcode-route-generator
v1.2.1
Published
A flexible Express.js route generator for MongoDB collections, providing advanced RESTful CRUD APIs with schema validation, relation population, and customizable middleware.
Readme
taughtcode-route-generator
A flexible Express.js route generator for MongoDB collections, providing advanced RESTful CRUD APIs with schema validation, relation population, and customizable middleware.
Features
- Automatic CRUD API: Instantly generate RESTful endpoints for any MongoDB collection.
- Schema Validation: Enforce data types, required fields, regex, and custom validation.
- Relation Population: Populate referenced documents from other collections.
- Custom Middleware: Add authentication, logging, or any Express middleware.
- API Metadata: Retrieve endpoint and schema information programmatically.
Installation
npm install taughtcode-route-generatorUsage
const express = require("express");
const { initializeRoutes } = require("taughtcode-route-generator");
const app = express();
app.use(express.json());
const mongoUri = "mongodb://localhost:27017/yourdb";
const collections = {
users: {
schema: {
name: { type: "string", required: true },
email: { type: "string", required: true, regex: /.+@.+\..+/ },
age: "number",
},
options: {
middleware: [], // Optional: Array of Express middleware
relations: {}, // Optional: { field: { collection, foreignField } }
},
},
};
(async () => {
const { routers, client } = await initializeRoutes(mongoUri, collections);
app.use("/api/users", routers.users);
// Add more collections as needed
app.listen(3000, () => console.log("Server running on port 3000"));
})();API Endpoints
- GET /api/:collection - Fetch all documents (supports filtering, pagination)
- GET /api/:collection/:id - Fetch a single document by ID
- POST /api/:collection - Create a new document
- PUT /api/:collection/:id - Update a document by ID
- DELETE /api/:collection/:id - Delete a document by ID
- DELETE /api/:collection/flash - Delete all documents in the collection
- GET /api/:collection/metadata - Get API metadata (endpoints, schema)
Schema Validation
Define schemas using simple types or advanced validation objects:
{
name: { type: 'string', required:
true },
age: 'number',
email: { type: 'string', regex: /.+@.
+\..+/ }
}Relations
Populate referenced documents by specifying relations:
relations: {
posts: { collection: 'posts',
foreignField: '_id' }
}License
ISC
