Skip to content

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 total a 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 as Long, hence Number(item.qty).
  • Partial updates arrive as operators ($set). Recompute what depends on the changed fields there, as the second hook does.
  • Refusing: MongocampError.badRequest(...) answers 400 with your message, and nothing is written. Any other error answers 500.
HookPayload besides user and collectionName
mongocamp:document:beforeInsertdocuments
mongocamp:document:beforeReplacefilter, document
mongocamp:document:beforeUpdatefilter, update, many
mongocamp:document:beforeDeletefilter, many
mongocamp:document:beforeReadscopes 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.

Released under the MIT License.