Extensions
Extensions are Nitro 3 plugins: a definePlugin file in server/plugins/ that hooks into the server through Nitro's own hook system.
ts
// server/plugins/mongocamp.ts
import { metrics } from '@sfxcode/mongocamp-server-core'
import { definePlugin } from 'nitro'
export default definePlugin((nitroApp) => {
// the started server, awaited before the first request is answered
nitroApp.hooks.hook('mongocamp:ready', async (server) => {
await server.use(metrics())
server.registerJobHandler('my.app.ReportJob', sendReport)
})
// every event of the server is a hook: mongocamp:<event>
nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
})| Need | How |
|---|---|
| React to changes (audit log, cache invalidation, webhooks) | Events: mongocamp:<event> hooks |
| Scheduled work | Jobs: handlers by class name, cron in croner syntax |
| Own endpoints | Custom routes: Nitro or Nuxt routes next to the API |
| Logs and metrics | Wide events with evlog, the database request log and Prometheus metrics |
Files are stored in GridFS.
Hooks
| Hook | Argument | When |
|---|---|---|
mongocamp:ready | the server (MongocampServer) | once, after the start and before the first request is answered |
mongocamp:<event> | the event | for every event, e.g. mongocamp:document:update, mongocamp:user:login |
The hooks are typed: the Nuxt module adds them to NitroRuntimeHooks, so nitroApp.hooks.hook('mongocamp:document:update', event => ...) knows the fields of the event.
Register the hooks in the plugin itself, at startup. The server reads expensive parts of an event (the old values of updated documents, the user of a request) only for hooks that have a listener.
Where plugins live
- Nuxt app with the embedded server:
server/plugins/*.tsof the application.useMongocampCore()still gives the server anywhere in server code. - Standalone server:
apps/server/plugins/and thepluginslist ofapps/server/nitro.config.ts; build your own image from it. - Own host:
connectHooks(server, hooks)of the core connects anyhookableinstance; or useserver.events.on(...)andserver.use(...)directly.
