mongodb-dynamic-api
v4.23.0
Published
Auto generated CRUD API for MongoDB using NestJS
Maintainers
Readme
[!WARNING] v4 — Breaking changes. Dual-token auth (
accessToken+refreshToken), new default expiry (expiresIn: '15m'), 2 new endpoints (/auth/refresh-token,/auth/logout).🔄 Dual-token authentication
Login and register now return
{ accessToken, refreshToken }instead of a single token. The/auth/refresh-tokenendpoint now requires the refresh token.⏱️ New default expiration times
| Token | v3 | v4 | |---|---|---| | Access token (
expiresIn) |'1d'|'15m'| | Refresh token (refreshTokenExpiresIn) | — |'7d'|If your app relied on the
'1d'lifetime, set it explicitly:jwt: { expiresIn: '1d' }.🆕 Two new endpoints
| Endpoint | Description | |---|---| |
POST /auth/refresh-token| Get a new token pair using the refresh token | |POST /auth/logout| Invalidate the refresh token server-side (204 No Content) |🔒 New options in
useAuth
jwt.refreshSecret— dedicated signing secret for refresh tokensrefreshToken.refreshTokenField— entity field storing the bcrypt hash (server-side revocation)refreshToken.useCookie— send/read refresh token via httpOnly cookie📖 Full details: README/authentication.md → Migration Guide
✨ Features
🚀 Zero Boilerplate Full CRUD REST API generated from a single schema definition.
🔐 JWT Authentication Dual-token (access + refresh), 8 built-in endpoints, cookie mode, server-side revocation.
🔓 Passwordless / OTP ⭐ Magic-link / OTP login flow with configurable token delivery.
🛡️ Authorization
Ability predicates — per-route access control in filter or throw mode.
⚡ Smart Caching
Global HTTP cache with auto-invalidation, disableCache per route or controller.
✅ Validation
class-validator integration, configurable ValidationPipe globally or per route.
📡 WebSockets
Socket.IO support, room-targeted broadcast, onConnection hook, debug mode.
🟢 Presence ⭐ Real-time online/offline tracking — InMemory or Redis adapter.
🔁 Callbacks
beforeSave, afterSave, beforeDelete hooks with typed context + authenticated user.
🌊 Cascade Delete ⭐
Cross-collection cascades with beforeDeleteCallback and soft-delete support.
🎛️ Custom Routes ⭐
Add any HTTP method with a custom service and WebSocket gateway in forFeature.
🏷️ Field Decorators ⭐
@DerivedField for computed values, @ProtectedField for runtime-stripped fields.
🔍 Aggregate + Pagination
MongoDB aggregation pipelines via toPipeline, auto-paginated with $facet.
📚 Swagger UI Auto-generated OpenAPI documentation for every route, zero configuration.
All dependencies included —
@nestjs/mongoose,@nestjs/jwt,@nestjs/swagger,class-validator,socket.ioand more. No extra installs.
⚡ Quick Start
1 — Configure the root module
// src/app.module.ts
import { Module } from '@nestjs/common';
import { DynamicApiModule } from 'mongodb-dynamic-api';
@Module({
imports: [
DynamicApiModule.forRoot(process.env.MONGODB_URI),
],
})
export class AppModule {}2 — Define your entity
// src/users/user.entity.ts
import { Prop, Schema } from '@nestjs/mongoose';
import { BaseEntity } from 'mongodb-dynamic-api';
import { IsEmail, IsNotEmpty } from 'class-validator';
@Schema({ collection: 'users' })
export class User extends BaseEntity {
@IsNotEmpty()
@Prop({ type: String, required: true })
name: string;
@IsEmail()
@Prop({ type: String, required: true, unique: true })
email: string;
}
BaseEntityautomatically providesid,createdAt,updatedAtand excludes_id/__vfrom responses.
3 — Generate the API
// src/users/users.module.ts
import { Module } from '@nestjs/common';
import { DynamicApiModule } from 'mongodb-dynamic-api';
import { User } from './user.entity';
@Module({
imports: [
DynamicApiModule.forFeature({
entity: User,
controllerOptions: { path: 'users' },
}),
],
})
export class UsersModule {}Register UsersModule in AppModule, run npm run start:dev — your API is live at http://localhost:3000/users. 🎉
📡 Generated Endpoints
| Route Type | Method | Path | Description |
|:-----------|:------:|:-----|:------------|
| GetMany | GET | /users | List all — supports MongoDB query params |
| GetOne | GET | /users/:id | Get a single document by ID |
| CreateMany | POST | /users/many | Bulk create — body: { list: User[] } |
| CreateOne | POST | /users | Create a single document |
| ReplaceOne | PUT | /users/:id | Full replacement |
| UpdateMany | PATCH | /users | Partial update — query: ?ids[]= |
| UpdateOne | PATCH | /users/:id | Partial update by ID |
| DeleteMany | DELETE | /users | Delete multiple — query: ?ids[]= |
| DeleteOne | DELETE | /users/:id | Delete by ID |
| DuplicateMany | POST | /users/duplicate | Clone multiple with field overrides |
| DuplicateOne | POST | /users/duplicate/:id | Clone one with field overrides |
| Aggregate | GET | /users/aggregate | Custom aggregation pipeline (requires Query DTO) |
Use the
routesarray inforFeatureto cherry-pick, exclude, or fine-tune any route individually.
📚 Documentation
| Feature | Description | Guide |
|:--------|:------------|:-----:|
| 🗂️ Entities | BaseEntity, SoftDeletableEntity, timestamps, JSON transform | View |
| 🗃️ Schema Options | Indexes, lifecycle hooks, custom schema initialization | View |
| 🔐 Authentication | Dual-token JWT, 8 endpoints, cookie mode, revocation, OTP, per-route rate limiting ⭐ | View |
| 🛡️ Authorization | Ability predicates, filter vs throw mode | View |
| ⚡ Caching | Global cache, auto-purge endpoint, disableCache option ⭐ | View |
| ✅ Validation | class-validator, global + per-route ValidationPipe, DB-aware @IsUnique/@EntityExists ⭐ | View |
| 📡 WebSockets | Socket.IO, room-targeted broadcast, onConnection, debug ⭐ | View |
| 🟢 Presence | Online/offline tracking, InMemory & Redis adapters ⭐ | View |
| 🔁 Callbacks | beforeSave, afterSave, beforeDelete, typed contexts ⭐ | View |
| 🔄 Versioning | URI-based API versioning | View |
| 📚 Swagger UI | Auto-generated OpenAPI docs, visibility decorators | View |
| 🗂️ Route Config | DTOs, cascade delete (atomic ⭐), predicates, subPath, interceptors, populate, auditLog ⭐ New | View |
| 🎛️ Controller Config | forFeature options, customRoutes, extraProviders ⭐ | View |
| 🐞 Debugging | MONGODB_DYNAMIC_API_LOGGER levels, WS debug mode, where each log comes from ⭐ | View |
| 🩺 Health Check | GET /health readiness probe, DynamicApiHealthModule ⭐ New | View |
| 🧪 Testing | createDynamicApiTestingApp, in-memory MongoDB, zero Docker ⭐ New | View |
| 🏗️ Schematics | nest g -c mongodb-dynamic-api resource <name> — scaffold entity + module in one command ⭐ New | View |
[!NOTE] Key reminders:
BaseEntityauto-enables timestamps — notimestamps: trueneeded in@Schema()- Soft delete: extend
SoftDeletableEntityto getisDeleted+deletedAtfields- Version strings must be numeric (
'1','2'), not semver- WebSocket auth event names are fixed:
auth-login,auth-register,auth-refresh-token,auth-logout…- CRUD WS events auto-generated:
kebabCase(routeType + '/' + displayedName)- Ability predicate signature:
(user, body?) => booleanfor auth,(entity, user) => booleanfor CRUD
License
MIT — see LICENSE
Made with ❤️ by Mickaël NODANCHE
