5. Hooks
Rules beyond the behaviours are before-hooks: functions in a Nitro plugin that run before a write. They are awaited, may change the documents, and refuse the write by throwing. They run for every writer: the API, the client composables and the server code of step 9.
The total of an order is computed here, and a new order cannot be shipped:
ts
import { MongocampError } from '@sfxcode/mongocamp-server-core'
import { definePlugin } from 'nitro'
type Item = { qty: unknown, price: unknown }
/**
* The sum of the items. A before-hook sees the documents of every collection as `Record<string, unknown>`, with driver values: whole
* numbers arrive as `Long`, hence `Number(...)`. The schema validates after the hooks, so a wrong item is still refused.
*/
function totalOf(items: unknown): number {
return Array.isArray(items) ? (items as Item[]).reduce((sum, item) => sum + Number(item.qty) * Number(item.price), 0) : 0
}
export default definePlugin((nitroApp) => {
nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ collectionName, documents }) => {
if (collectionName !== 'orders') {
return
}
for (const order of documents) {
if (order.status === 'shipped') {
// refuses the whole request, nothing is written
throw MongocampError.badRequest('a new order cannot be shipped yet')
}
order.total = totalOf(order.items)
}
})
nitroApp.hooks.hook('mongocamp:document:beforeUpdate', ({ collectionName, update }) => {
// a partial update arrives as operators: recompute the total when the items change
const set = update.$set as Record<string, unknown> | undefined
if (collectionName === 'orders' && set?.items !== undefined) {
set.total = totalOf(set.items)
}
})
})How this fits together:
- Order of the stages: the guard of the behaviours drops the protected
totala client sent, then your hook sets it, then the schema validates, then the behaviours set their fields. So the hook may write a protected field, and its result is still validated. - Driver values: a hook sees the documents of every collection as
Record<string, unknown>with MongoDB driver values. Whole numbers arrive asLong, henceNumber(item.qty). - Partial updates arrive as operators (
$set). Recompute what depends on the changed fields there, as the second hook does. - Refusing:
MongocampError.badRequest(...)answers400with your message, and nothing is written. Any other error answers500.
| Hook | Payload besides user and collectionName |
|---|---|
mongocamp:document:beforeInsert | documents |
mongocamp:document:beforeReplace | filter, document |
mongocamp:document:beforeUpdate | filter, update, many |
mongocamp:document:beforeDelete | filter, many |
mongocamp:document:beforeRead | scopes to narrow every read |
When to use which:
- the schema for the shape of one document;
- a behaviour for a rule it covers;
- a hook for rules that compute, look at other documents, or depend on the user.
More in Events and hooks.
