|
1 | 1 | # Plugin System |
2 | 2 |
|
3 | | -Plugins allow you to extend the core functionality of ObjectQL by intercepting lifecycle events, modifying metadata, or injecting new services. |
| 3 | +Plugins are the primary way to extend ObjectQL. They allow you to bundle behavior, schema modifications, and logic (hooks/actions) into reusable units. |
4 | 4 |
|
5 | | -## The Plugin Interface |
| 5 | +## 1. Anatomy of a Plugin |
6 | 6 |
|
7 | | -A plugin is simply a class (or object) implementing `ObjectQLPlugin`. |
| 7 | +A plugin is simply an object that implements the `ObjectQLPlugin` interface. |
8 | 8 |
|
9 | 9 | ```typescript |
10 | 10 | import { IObjectQL } from '@objectql/types'; |
11 | 11 |
|
12 | 12 | export interface ObjectQLPlugin { |
| 13 | + /** |
| 14 | + * The unique name of the plugin |
| 15 | + */ |
13 | 16 | name: string; |
| 17 | + |
| 18 | + /** |
| 19 | + * Called during initialization, before drivers connect. |
| 20 | + * @param app The ObjectQL instance |
| 21 | + */ |
14 | 22 | setup(app: IObjectQL): void | Promise<void>; |
15 | 23 | } |
16 | 24 | ``` |
17 | 25 |
|
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. |
| 26 | +## 2. Creating Plugins |
19 | 27 |
|
20 | | -## Capabilities |
| 28 | +You can define plugins in two styles: **Object** or **Class**. |
21 | 29 |
|
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()`. |
| 30 | +### Option A: Object Style (Simpler) |
| 31 | +Useful for stateless, simple logic or one-off modifications. |
25 | 32 |
|
26 | | -## Example: Soft Delete Plugin |
| 33 | +```typescript |
| 34 | +const MySimplePlugin = { |
| 35 | + name: 'my-simple-plugin', |
| 36 | + setup(app) { |
| 37 | + app.on('before:create', 'user', async (ctx) => { |
| 38 | + console.log('Creating user...'); |
| 39 | + }); |
| 40 | + } |
| 41 | +}; |
| 42 | +``` |
27 | 43 |
|
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. |
| 44 | +### Option B: Class Style (Recommended) |
| 45 | +Useful when your plugin needs to maintain internal state, configuration, or complex initialization logic. |
32 | 46 |
|
33 | 47 | ```typescript |
34 | | -import { ObjectQLPlugin, IObjectQL } from '@objectql/types'; |
| 48 | +class MyComplexPlugin implements ObjectQLPlugin { |
| 49 | + name = 'my-complex-plugin'; |
| 50 | + private config; |
35 | 51 |
|
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 | | - } |
| 52 | + constructor(config = {}) { |
| 53 | + this.config = config; |
| 54 | + } |
47 | 55 |
|
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 |
| 56 | + async setup(app: IObjectQL) { |
| 57 | + // Access config here |
| 58 | + if (this.config.enableLogging) { |
| 59 | + app.on('before:*', '*', async (ctx) => { |
| 60 | + console.log(`[${ctx.event}] ${ctx.objectName}`); |
58 | 61 | }); |
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 | | - }); |
| 62 | + } |
70 | 63 | } |
71 | 64 | } |
72 | 65 | ``` |
73 | 66 |
|
74 | | -## Usage |
| 67 | +## 3. Loading Plugins |
75 | 68 |
|
76 | | -Plugins can be loaded in two ways: by instance or by package name. |
| 69 | +Plugins are passed to the `ObjectQL` constructor via the `plugins` array. The loader is very flexible. |
77 | 70 |
|
78 | | -### 1. By Instance (Local Development) |
| 71 | +### Method 1: Inline Instance |
| 72 | +Pass the plugin object or class instance directly. |
79 | 73 |
|
80 | 74 | ```typescript |
81 | 75 | const db = new ObjectQL({ |
82 | | - connection: 'sqlite://data.db', |
83 | 76 | plugins: [ |
84 | | - new SoftDeletePlugin() |
| 77 | + MySimplePlugin, // Object |
| 78 | + new MyComplexPlugin({}) // Class Instance |
85 | 79 | ] |
86 | 80 | }); |
87 | 81 | ``` |
88 | 82 |
|
89 | | -### 2. By Package Name (Distribution) |
90 | | - |
91 | | -If you have installed a plugin via npm (e.g. `npm install @objectql/plugin-audit`), you can simply pass its name. ObjectQL will automatically resolve and instantiate it. |
| 83 | +### Method 2: NPM Package (String) |
| 84 | +You can specify the package name as a string. ObjectQL uses `require()` (Node.js) to resolve it. |
92 | 85 |
|
93 | 86 | ```typescript |
94 | 87 | const db = new ObjectQL({ |
95 | | - connection: 'sqlite://data.db', |
96 | 88 | plugins: [ |
97 | | - '@objectql/plugin-audit' |
| 89 | + '@objectql/plugin-audit', // Searches node_modules |
| 90 | + './local-plugins/my-plugin' // Relative path |
98 | 91 | ] |
99 | 92 | }); |
100 | 93 | ``` |
101 | 94 |
|
102 | | -## Creating a Plugin Package |
| 95 | +#### Package Resolution Rules |
| 96 | +When loading from a string, ObjectQL tries to find the plugin in the exported module in this order: |
103 | 97 |
|
104 | | -To publish a plugin as an npm package: |
| 98 | +1. **Class Constructor**: If the module exports a Class (default or module.exports), it tries to instantiation it (`new Plugin()`). |
| 99 | +2. **Plugin Object**: If the module exports an object with a `setup` function, it uses it directly. |
| 100 | +3. **Default Export**: If the module has a `default` export, it checks that recursively. |
105 | 101 |
|
106 | | -1. Create a project exporting your plugin class/instance as the `default` export (or named export). |
107 | | -2. Ensure it implements `ObjectQLPlugin`. |
| 102 | +**Example Package (`node_modules/my-plugin/index.js`):** |
| 103 | +```javascript |
| 104 | +// This works |
| 105 | +module.exports = class MyPlugin { ... } |
108 | 106 |
|
109 | | -**index.ts** |
110 | | -```typescript |
111 | | -import { ObjectQLPlugin, IObjectQL } from '@objectql/types'; |
| 107 | +// This also works |
| 108 | +module.exports = { name: '..', setup: () => {} } |
| 109 | + |
| 110 | +// This also works (ESM/TS) |
| 111 | +export default class MyPlugin { ... } |
| 112 | +``` |
| 113 | + |
| 114 | +## 4. What can Plugins do? |
112 | 115 |
|
113 | | -export default class MyPlugin implements ObjectQLPlugin { |
114 | | - name = 'my-plugin'; |
115 | | - setup(app: IObjectQL) { |
116 | | - // ... |
| 116 | +The `setup(app)` method gives you full access to the `ObjectQL` instance. |
| 117 | + |
| 118 | +### A. Manipulate Metadata (Schema) |
| 119 | +Plugins have full control over the schema. You can modify existing objects or register new ones. |
| 120 | + |
| 121 | +**Example 1: Injecting a global field** |
| 122 | +```typescript |
| 123 | +setup(app) { |
| 124 | + const allObjects = app.metadata.list('object'); |
| 125 | + for (const obj of allObjects) { |
| 126 | + // Add 'createdAt' to every object if missing |
| 127 | + if (!obj.fields.createdAt) { |
| 128 | + obj.fields.createdAt = { type: 'datetime' }; |
| 129 | + } |
117 | 130 | } |
118 | 131 | } |
119 | 132 | ``` |
120 | 133 |
|
121 | | -Then in another project: |
122 | | -```bash |
123 | | -npm install my-plugin-package |
| 134 | +**Example 2: Registering a new Object** |
| 135 | +Plugins can bundle their own data models (e.g. an audit log table). |
| 136 | + |
| 137 | +```typescript |
| 138 | +setup(app) { |
| 139 | + app.registerObject({ |
| 140 | + name: 'audit_log', |
| 141 | + fields: { |
| 142 | + action: { type: 'string' }, |
| 143 | + userId: { type: 'string' }, |
| 144 | + timestamp: { type: 'datetime' } |
| 145 | + } |
| 146 | + }); |
| 147 | +} |
124 | 148 | ``` |
| 149 | + |
| 150 | +**Example 3: Scanning a Directory** |
| 151 | +Plugins can also scan a directory to load `*.object.yml` files, just like the main application. This is useful for bundling a set of objects. |
| 152 | + |
| 153 | +```typescript |
| 154 | +import * as path from 'path'; |
| 155 | + |
| 156 | +setup(app) { |
| 157 | + // Scan the 'objects' folder inside the plugin directory |
| 158 | + const objectsDir = path.join(__dirname, 'objects'); |
| 159 | + app.loadFromDirectory(objectsDir); |
| 160 | +} |
| 161 | +``` |
| 162 | + |
| 163 | +### B. Register Global Hooks |
| 164 | +Listen to lifecycle events on specific objects or `*` (wildcard). |
| 165 | + |
| 166 | +```typescript |
| 167 | +setup(app) { |
| 168 | + app.on('before:delete', '*', async (ctx) => { |
| 169 | + if (ctx.objectName === 'system_log') { |
| 170 | + throw new Error("Logs cannot be deleted"); |
| 171 | + } |
| 172 | + }); |
| 173 | +} |
| 174 | +``` |
| 175 | + |
| 176 | +### C. Register Custom Actions |
| 177 | +Add new capabilities to objects. |
| 178 | + |
125 | 179 | ```typescript |
126 | | -// objectql.config.ts |
127 | | -plugins: ['my-plugin-package'] |
| 180 | +setup(app) { |
| 181 | + // Usage: objectql.executeAction('user', 'sendEmail', { ... }) |
| 182 | + app.registerAction('user', 'sendEmail', async (ctx) => { |
| 183 | + await emailService.send(ctx.args.to, ctx.args.body); |
| 184 | + }); |
| 185 | +} |
128 | 186 | ``` |
| 187 | + |
| 188 | +### D. Custom Metadata Loaders |
| 189 | +Plugins can register new loaders to scan for custom file types (e.g. `*.workflow.yml`). This allows ObjectQL to act as a unified metadata engine. |
| 190 | + |
| 191 | +```typescript |
| 192 | +import * as yaml from 'js-yaml'; |
| 193 | + |
| 194 | +setup(app) { |
| 195 | + app.addLoader({ |
| 196 | + name: 'workflow-loader', |
| 197 | + glob: ['**/*.workflow.yml'], |
| 198 | + handler: (ctx) => { |
| 199 | + const doc = yaml.load(ctx.content); |
| 200 | + const workflowName = doc.name; |
| 201 | + |
| 202 | + // Register into MetadataRegistry with a custom type |
| 203 | + ctx.registry.register('workflow', { |
| 204 | + type: 'workflow', |
| 205 | + id: workflowName, |
| 206 | + path: ctx.file, |
| 207 | + content: doc |
| 208 | + }); |
| 209 | + } |
| 210 | + }); |
| 211 | +} |
| 212 | +``` |
| 213 | + |
| 214 | +## 5. Scope Isolation |
| 215 | + |
| 216 | + |
| 217 | +When a plugin is loaded via **Package Name** (Method 2), ObjectQL automatically marks the hooks and actions registered by that plugin with its package name. |
| 218 | + |
| 219 | +This allows `app.removePackage('@objectql/plugin-auth')` to cleanly remove all hooks and actions associated with that plugin, without affecting others. |
0 commit comments