Plugins
Plugins
Database plugins allow you to define reusable behaviors that can be applied to database models through the OpenSya runtime.
They are useful for shared logic such as:
- JSON serialization
- Soft delete
- Audit fields
- Slugs
- Timestamps
- Sensitive field cleanup
- Common schema transformations
Filesystem Structure
Database plugins are placed inside the server/database/plugins directory.
server/database/plugins/
├── to-json.ts
├── soft-delete.ts
└── audit.ts
Each plugin file is automatically discovered by the runtime.
Creating a Plugin
A database plugin is created using defineMongoosePlugin.
export default defineMongoosePlugin((schema) => {
schema.set('toJSON', {
depopulate: false,
schemaFieldsOnly: false,
transform(doc, ret) {
_.set(ret, 'id', ret._id?.toString());
_.unset(ret, '_id');
_.unset(ret, '__v');
return ret;
},
});
});
The plugin receives the Mongoose schema and can customize it before the model is registered.
Example: Clean JSON Output
A common use case is normalizing JSON responses before sending data to the client.
export default defineMongoosePlugin((schema) => {
schema.set('toJSON', {
depopulate: false,
schemaFieldsOnly: false,
transform(doc, ret) {
_.set(ret, 'id', ret._id?.toString());
_.unset(ret, '_id');
_.unset(ret, '__v');
_.unset(ret, 'password');
for (const key in ret) {
if (!Object.hasOwn(ret, key)) continue;
const data: any = ret[key];
if (data?.type !== 'Buffer') continue;
_.unset(ret, key);
}
return ret;
},
});
});
This plugin:
- Converts
_idtoid - Removes MongoDB internal fields
- Removes sensitive fields such as
password - Removes raw
Bufferfields from JSON output
Runtime Discovery
During startup, OpenSya automatically discovers database plugins from the filesystem.
server/database/plugins/clean-json.ts
↓
Discovered by OpenSya runtime
↓
Applied during model registration
The runtime integrates plugins into the generated backend runtime automatically.
Plugin Responsibilities
Plugins should be used for reusable database behaviors.
Good examples include:
| Plugin | Purpose |
|---|---|
clean-json.ts | Normalize JSON output and remove internal fields. |
soft-delete.ts | Add soft delete behavior to models. |
audit.ts | Add created by / updated by metadata. |
slug.ts | Generate slugs from model fields. |
Best Practices
Keep plugins small and focused.
A plugin should generally handle one reusable behavior.
Avoid putting business-specific logic inside global plugins. Business rules should usually live inside services.
Philosophy
Plugins help OpenSya keep database logic modular and reusable.
They allow recruitment and business infrastructures to evolve consistently while avoiding repeated schema logic across models.