Reference

Hooks

Lifecycle hooks in dnax Framework.

Hooks allow you to execute logic before and after database operations.

Available Hooks

HookDescription
beforeOperationBefore any operation
afterOperationAfter 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

ActionAvailable Meta
findparams, options
findOneparams, id
insertOnedata, result
insertManydata, result
updateOneupdate, id, result
updateManyupdate, ids, result
deleteOneid, result
deleteManyids, result
aggregatepipeline, result
Copyright © 2026