A lightweight and flexible REST API generator for Fastify and MongoDB. Create fully-featured CRUD APIs with minimal configuration.
npm install @ferjssilva/fast-crud-api- fastify (peer dependency)
- mongoose (peer dependency)
- fastify-plugin
- π Full CRUD operations out of the box
- π Automatic pagination
- π Text search across string fields
- π Reference population support
- π± Nested routes for relationships
- π― Method restrictions per model
- οΏ½ User-scoped resources with automatic filtering
- οΏ½π Query building with filtering and sorting
- β‘ MongoDB integration with proper document transformation
- π Clean REST API endpoints
- π¨ Comprehensive error handling
- β 100% Test Coverage
const fastify = require('fastify')()
const mongoose = require('mongoose')
const fastCrudApi = require('@ferjssilva/fast-crud-api')
// Your mongoose models
const User = require('./models/User')
const Post = require('./models/Post')
// Register the plugin
fastify.register(fastCrudApi, {
prefix: '/api',
models: [User, Post],
methods: {
// Optional: restrict methods per model
users: ['GET', 'POST', 'PUT', 'DELETE'],
posts: ['GET', 'POST']
},
userScoped: ['posts'] // Optional: automatically filter resources by userId
})GET /api/users?page=1&limit=10
GET /api/users?sort={"createdAt":-1}
GET /api/users?name=John&age=25
GET /api/users?search=johnGET /api/users/:id
GET /api/users/:id?populate=postsPOST /api/users
Content-Type: application/json
{
"name": "John Doe",
"email": "[email protected]"
}PUT /api/users/:id
Content-Type: application/json
{
"name": "John Updated"
}DELETE /api/users/:idGET /api/users/:userId/postsAutomatically filter and secure resources by user ID. Perfect for multi-tenant applications where users should only access their own data.
fastify.register(fastCrudApi, {
prefix: '/api',
models: [User, Post, UserHabit],
userScoped: ['user-habits'] // Resources that require user isolation
})How it works:
-
Authentication Required: User-scoped resources require
request.userIdto be set (typically by an authentication middleware) -
Automatic Filtering:
- GET requests automatically filter by
userId - POST requests automatically inject
userIdinto new documents - PUT/DELETE requests verify ownership atomically
- GET requests automatically filter by
-
Security:
- Users cannot access other users' data
- Users cannot modify
userIdon their resources - Ownership checks prevent TOCTOU vulnerabilities
Example with Authentication:
// Authentication middleware to set request.userId
fastify.addHook('preHandler', async (request, reply) => {
const token = request.headers.authorization?.split(' ')[1];
const user = await verifyToken(token);
if (user) {
request.userId = user.id; // Set userId for user-scoped resources
}
});
// User-scoped resources
fastify.register(fastCrudApi, {
prefix: '/api',
models: [UserHabit, UserProfile],
userScoped: ['user-habits', 'user-profiles']
});Usage:
# List user's own habits (automatically filtered)
GET /api/user-habits
Authorization: Bearer <token>
# Create habit (userId injected automatically)
POST /api/user-habits
Authorization: Bearer <token>
Content-Type: application/json
{
"habitId": "exercise-daily",
"frequency": "daily"
}
# Update only if user owns the resource
PUT /api/user-habits/:id
Authorization: Bearer <token>
# Delete only if user owns the resource
DELETE /api/user-habits/:id
Authorization: Bearer <token>{
"data": [...],
"pagination": {
"total": 100,
"page": 1,
"limit": 10,
"pages": 10
}
}{
"id": "...",
"field1": "value1",
"field2": "value2"
}{
"error": "ErrorType",
"message": "Error description",
"details": [] // Optional validation details
}The library is organized in a modular structure for better maintainability:
src/
βββ index.js # Main plugin module
βββ utils/
β βββ document.js # Document transformation utilities
β βββ query.js # Query building utilities
βββ middleware/
β βββ error-handler.js # Error handling middleware
β βββ user-scope.js # User-scoped resource middleware
βββ routes/
β βββ crud.js # CRUD route handlers
β βββ nested.js # Nested route handlers
βββ validators/
βββ method.js # Method validation utilities
If you encounter any issues or have suggestions for improvements, please open an issue on our GitHub repository. We appreciate your feedback and contributions!
The library includes comprehensive unit tests to ensure the correct functioning of all components:
# Run all tests
npm test
# Run tests with coverage report
npm run test:coverage
# Run tests in watch mode (useful during development)
npm run test:watchCode coverage results:
- Lines of code: 100%
- Functions: 100%
- Branches: 100%
- Statements: 100%
We've achieved complete coverage for all components:
- Utils: 100%
- Validators: 100%
- Middleware: 100%
- Routes: 100%
ISC License