Reference
Hooks
Lifecycle hooks in dnax Framework.
Hooks allow you to execute logic before and after database operations.
Available Hooks
| Hook | Description |
|---|---|
beforeOperation | Before any operation |
afterOperation | After any operation |
Define Hooks
import { define } from '@dnax/core';
export default define.Collection({
slug: 'users',
fields: [
{ name: 'name', type: 'string' },
],
hooks: {
beforeOperation: async ({ action, rest, meta }) => {
console.log(`Before ${action}:`, meta);
},
afterOperation: async ({ action, rest, meta }) => {
console.log(`After ${action}:`, meta.result);
},
},
});
Hook Context
The hook receives an object with these properties:
{
rest: useRest; // Rest instance
action: string; // Action name
meta: {
collection: string;
data?: any;
result?: any;
params?: any;
filter?: any;
update?: any;
ids?: string[];
id?: string;
};
}
Before Operation
Use beforeOperation to:
- Modify data before insertion
- Validate custom conditions
- Log operations
- Add default values
hooks: {
beforeOperation: async ({ action, rest, meta, data }) => {
if (action === 'insertOne') {
// Add createdBy field
meta.data.createdBy = 'system';
}
if (action === 'deleteOne') {
// Soft delete instead of hard delete
await rest.updateOne(meta.collection, meta.id, {
$set: { deletedAt: new Date(), status: 'deleted' }
});
return false; // Skip original operation
}
},
}
After Operation
Use afterOperation to:
- Trigger notifications
- Log results
- Cleanup
hooks: {
afterOperation: async ({ action, rest, meta }) => {
if (action === 'insertOne') {
console.log('Created document:', meta.result._id);
}
if (action === 'updateMany') {
console.log(`Updated ${meta.result.modifiedCount} documents`);
}
},
}
Access Hook Meta
| Action | Available Meta |
|---|---|
find | params, options |
findOne | params, id |
insertOne | data, result |
insertMany | data, result |
updateOne | update, id, result |
updateMany | update, ids, result |
deleteOne | id, result |
deleteMany | ids, result |
aggregate | pipeline, result |