|
| 1 | +# Plugin System |
| 2 | + |
| 3 | +Plugins allow you to extend the core functionality of ObjectQL by intercepting lifecycle events, modifying metadata, or injecting new services. |
| 4 | + |
| 5 | +## The Plugin Interface |
| 6 | + |
| 7 | +A plugin is simply a class (or object) implementing `ObjectQLPlugin`. |
| 8 | + |
| 9 | +```typescript |
| 10 | +import { IObjectQL } from '@objectql/types'; |
| 11 | + |
| 12 | +export interface ObjectQLPlugin { |
| 13 | + name: string; |
| 14 | + setup(app: IObjectQL): void | Promise<void>; |
| 15 | +} |
| 16 | +``` |
| 17 | + |
| 18 | +The `setup` method is called during `db.init()`, **before** the database drivers are initialized. This gives plugins a chance to modify the schema metadata. |
| 19 | + |
| 20 | +## Capabilities |
| 21 | + |
| 22 | +1. **Metadata Mutation**: Modify `app.metadata` to inject fields or create objects dynamically. |
| 23 | +2. **Global Hooks**: Use `app.on()` to listen to events on *all* objects. |
| 24 | +3. **Action Registry**: Register new actions via `app.registerAction()`. |
| 25 | + |
| 26 | +## Example: Soft Delete Plugin |
| 27 | + |
| 28 | +This plugin automatically handles "Soft Delete" logic: |
| 29 | +1. Injects an `isDeleted` field to all objects. |
| 30 | +2. Intercepts `delete` operations to perform an update instead. |
| 31 | +3. Intercepts `find` operations to filter out deleted records. |
| 32 | + |
| 33 | +```typescript |
| 34 | +import { ObjectQLPlugin, IObjectQL } from '@objectql/types'; |
| 35 | + |
| 36 | +export class SoftDeletePlugin implements ObjectQLPlugin { |
| 37 | + name = 'soft-delete'; |
| 38 | + |
| 39 | + setup(app: IObjectQL) { |
| 40 | + // 1. Inject 'isDeleted' field |
| 41 | + const objects = app.metadata.list('object'); |
| 42 | + for (const obj of objects) { |
| 43 | + if (!obj.fields.isDeleted) { |
| 44 | + obj.fields.isDeleted = { type: 'boolean', default: false }; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // 2. Intercept DELETE -> UPDATE |
| 49 | + app.on('before:delete', '*', async (ctx) => { |
| 50 | + // Prevent actual deletion |
| 51 | + ctx.preventDefault(); |
| 52 | + |
| 53 | + // Execute internal update |
| 54 | + // We use a custom action or system updated to bypass recursion if needed |
| 55 | + await app.executeAction(ctx.objectName, 'internalUpdate', { |
| 56 | + id: ctx.id, |
| 57 | + isDeleted: true |
| 58 | + }); |
| 59 | + }); |
| 60 | + |
| 61 | + // 3. Intercept FIND -> Filter |
| 62 | + app.on('before:find', '*', async (ctx) => { |
| 63 | + if (ctx.query) { |
| 64 | + ctx.query.filters = { |
| 65 | + ...(ctx.query.filters || {}), |
| 66 | + isDeleted: false |
| 67 | + } |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +## Usage |
| 75 | + |
| 76 | +```typescript |
| 77 | +const db = new ObjectQL({ |
| 78 | + connection: 'sqlite://data.db', |
| 79 | + plugins: [ |
| 80 | + new SoftDeletePlugin() |
| 81 | + ] |
| 82 | +}); |
| 83 | +``` |
0 commit comments