|
1 | 1 | # Hooks (Triggers) |
2 | 2 |
|
3 | | -Hooks allow you to execute server-side logic before or after database operations. They are defined in a separate `*.hook.ts` file or registered dynamically. |
| 3 | +Hooks allow you to execute server-side logic before or after database operations. They are the primary mechanism for implementing business logic, validation, and side effects in ObjectQL. |
4 | 4 |
|
5 | | -## 1. Supported Hooks |
| 5 | +## 1. Overview |
6 | 6 |
|
7 | | -| Hook | Description | Context Properties | |
8 | | -| :--- | :--- | :--- | |
9 | | -| `beforeFind` | Before a query is executed. | `query` | |
10 | | -| `afterFind` | After a query is executed (results available). | `query`, `result` | |
11 | | -| `beforeCreate` | Before a record is inserted. | `doc` | |
12 | | -| `afterCreate` | After a record is inserted. | `doc`, `result`, `id` | |
13 | | -| `beforeUpdate` | Before a record is updated. | `id`, `doc`, `query` | |
14 | | -| `afterUpdate` | After a record is updated. | `id`, `doc`, `result` | |
15 | | -| `beforeDelete` | Before a record is deleted. | `id`, `query` | |
16 | | -| `afterDelete` | After a record is deleted. | `id`, `result` | |
| 7 | +Hook files should be named `[object_name].hook.ts` and placed alongside your `*.object.yml` files. |
17 | 8 |
|
18 | | -> **Note on Aggregation:** |
19 | | -> If `query.aggregate` or `query.groupBy` is present (Aggregation Query), the `result` in `afterFind` will be an array of raw aggregation objects (e.g. `[{ total: 100, category: 'A' }]`) instead of standard object instances. |
| 9 | +### The "Optimal" Design Philosophy |
20 | 10 |
|
21 | | -## 2. Hook Implementation |
| 11 | +Unlike traditional ORMs that provide generic contexts, ObjectQL hooks are **Typed**, **Context-Aware**, and **Smart**. |
| 12 | + |
| 13 | +* **Type Safety**: Contexts are generic (e.g., `UpdateHookContext<Project>`), giving you autocomplete for fields. |
| 14 | +* **Separation of Concerns**: `before` hooks focus on validation/mutation; `after` hooks focus on side-effects. |
| 15 | +* **Change Tracking**: Built-in helpers like `isModified()` simplify "diff" logic. |
| 16 | + |
| 17 | +## 2. Supported Hooks |
| 18 | + |
| 19 | +| Hook | Operation | Context Properties | Purpose | |
| 20 | +| :--- | :--- | :--- | :--- | |
| 21 | +| `beforeFind` | Find/Count | `query` | Modify query filters, enforce security. | |
| 22 | +| `afterFind` | Find/Count | `query`, `result` | Transform results, logging. | |
| 23 | +| `beforeCreate` | Create | `data` | Validate inputs, set defaults, calculate fields. | |
| 24 | +| `afterCreate` | Create | `data`, `result` | Send welcome emails, create related records. | |
| 25 | +| `beforeUpdate` | Update | `id`, `data`, `previousData` | Validate state transitions (e.g., draft -> published). | |
| 26 | +| `afterUpdate` | Update | `id`, `data`, `previousData` | Notifications based on changes. | |
| 27 | +| `beforeDelete` | Delete | `id` | Check dependency constraints. | |
| 28 | +| `afterDelete` | Delete | `id`, `result` | Cleanup external resources (S3 files, etc). | |
| 29 | + |
| 30 | +## 3. Implementation |
| 31 | + |
| 32 | +The recommended way to define hooks is using the `ObjectHookDefinition` interface. |
22 | 33 |
|
23 | 34 | ```typescript |
24 | | -import { ObjectQL } from '@objectql/core'; |
| 35 | +// src/objects/project.hook.ts |
| 36 | +import { ObjectHookDefinition } from '@objectql/types'; |
| 37 | +import { Project } from './types'; // Your generated type |
| 38 | + |
| 39 | +const hooks: ObjectHookDefinition<Project> = { |
| 40 | + |
| 41 | + // 1. Validation & Defaulting |
| 42 | + beforeCreate: async ({ data, user, api }) => { |
| 43 | + if (!data.name) { |
| 44 | + throw new Error("Project name is required"); |
| 45 | + } |
| 46 | + |
| 47 | + // Auto-assign owner |
| 48 | + data.owner_id = user?.id; |
| 49 | + |
| 50 | + // Check uniqueness via API |
| 51 | + const existing = await api.count('project', [['name', '=', data.name]]); |
| 52 | + if (existing > 0) throw new Error("Name taken"); |
| 53 | + }, |
25 | 54 |
|
26 | | -// Inside your server-side loader |
27 | | -const objectql = new ObjectQL(); |
| 55 | + // 2. State Transition Logic |
| 56 | + beforeUpdate: async ({ data, previousData, isModified }) => { |
| 57 | + // 'previousData' is automatically fetched by the engine |
| 58 | + |
| 59 | + if (isModified('status')) { |
| 60 | + if (previousData.status === 'Completed' && data.status !== 'Completed') { |
| 61 | + throw new Error("Cannot reopen a completed project"); |
| 62 | + } |
| 63 | + } |
| 64 | + }, |
28 | 65 |
|
29 | | -objectql.registerHook('projects', 'beforeCreate', async (ctx) => { |
30 | | - if (ctx.doc.budget < 0) { |
31 | | - throw new Error("Budget cannot be negative"); |
| 66 | + // 3. Side Effects (Notifications) |
| 67 | + afterUpdate: async ({ isModified, data, api }) => { |
| 68 | + if (isModified('status') && data.status === 'Completed') { |
| 69 | + await api.create('notification', { |
| 70 | + message: `Project ${data.name} finished!`, |
| 71 | + user_id: data.owner_id |
| 72 | + }); |
| 73 | + } |
32 | 74 | } |
33 | | -}); |
| 75 | +}; |
| 76 | + |
| 77 | +export default hooks; |
| 78 | +``` |
| 79 | + |
| 80 | +## 4. Hook Context API |
| 81 | + |
| 82 | +The context object passed to your function is tailored to the operation. |
| 83 | + |
| 84 | +### 4.1 Base Properties (Available Everywhere) |
| 85 | +* `objectName`: string |
| 86 | +* `api`: The internal ObjectQL driver instance (for running queries). |
| 87 | +* `user`: The current user session. |
| 88 | +* `state`: A shared object to pass data from `before` to `after` hooks. |
| 89 | + |
| 90 | +### 4.2 Update Context (`beforeUpdate` / `afterUpdate`) |
| 91 | +* `data`: The partial object containing changes. |
| 92 | +* `previousData`: The full record **before** the update. |
| 93 | +* `isModified(field)`: Returns `true` if the field is present in `data` AND different from `previousData`. |
| 94 | + |
| 95 | +### 4.3 Query Context (`beforeFind`) |
| 96 | +* `query`: The AST of the query. You can inject extra filters here. |
| 97 | + |
| 98 | +```typescript |
| 99 | +beforeFind: async ({ query, user }) => { |
| 100 | + // Force multi-tenancy filter |
| 101 | + query.filters.push(['organization_id', '=', user.org_id]); |
| 102 | +} |
34 | 103 | ``` |
0 commit comments