Events
The server publishes typed events. In Nitro they are hooks named mongocamp:<event>. Events are notifications only:
- a listener never changes the answer of a request,
- a failing listener is logged and does not turn a successful request into an error.
Listening
A Nitro plugin of the application (Nuxt with the embedded server, or the standalone server):
// server/plugins/audit.ts
import type { MongocampServer } from '@sfxcode/mongocamp-server-core'
import { definePlugin } from 'nitro'
export default definePlugin((nitroApp) => {
let server: MongocampServer
nitroApp.hooks.hook('mongocamp:ready', (ready) => {
server = ready
})
nitroApp.hooks.hook('mongocamp:document:update', async (event) => {
await server.context.database.db().collection('audit').insertOne({
at: event.eventDate,
user: event.user.userId,
collection: event.collectionName,
before: event.oldValues,
result: event.updateResponse,
})
})
})Register the hooks when the plugin runs (at startup), as above. The server checks for listeners per event, so a hook that is never registered costs nothing.
With your own host, without Nitro:
import { createMongocampServer } from '@sfxcode/mongocamp-server-core'
const server = await createMongocampServer({
on: { 'server:started': () => console.log('ready') }, // listeners that must see the start
})
const remove = server.events.on('user:login', event => console.log(event.user.userId))
remove() // unsubscribeserver.events.observe((name, payload) => ...) sees every event without counting as a listener (e.g. for metrics).
Cost
Expensive parts of an event, such as the old values of updated documents or the user of an HTTP request, are only read when a hook or listener for that event is registered.
Before-hooks
Since 2.3 the document writes have before-hooks. Unlike events they run before the write, are awaited, and can change or refuse it:
// server/plugins/orders.ts
import { MongocampError } from '@sfxcode/mongocamp-server-core'
import { definePlugin } from 'nitro'
export default definePlugin((nitroApp) => {
nitroApp.hooks.hook('mongocamp:document:beforeInsert', ({ collectionName, documents, user }) => {
if (collectionName === 'orders') {
for (const document of documents) {
document.createdBy = user.userId
}
}
})
nitroApp.hooks.hook('mongocamp:document:beforeDelete', ({ collectionName }) => {
if (collectionName === 'invoices') {
throw MongocampError.forbidden('invoices are never deleted')
}
})
})| Hook | Payload (besides user, collectionName, databaseName) | Routes |
|---|---|---|
mongocamp:document:beforeInsert | documents, source (insert, insertMany, import), lines (import) | insert, insert many, import (once per batch of 1000 lines) |
mongocamp:document:beforeReplace | filter, document | PATCH …/documents/{id} |
mongocamp:document:beforeUpdate | filter, update (the operators), many | PATCH …/{id}/partial, many/update |
mongocamp:document:beforeDelete | filter, many | DELETE …/{id}, many/delete |
- They run after the authorization and the decoding of the body; the values are driver values (
ObjectId,Date, whole numbers asLong). - Change the write in place on the payload (
event.filter = { ...event.filter, tenant }). - Refuse it by throwing: a
MongocampErroris answered with its status (MongocampError.validation(issues)for invalid documents, see Errors), any other error with500. Nothing is written; a refused import batch rolls back the batches stored before. - An insert hook may change the documents but not their number (positions name the documents in errors and import lines).
- Replacing a document must not change its
_id(400). - The schemas of declared collections validate after all before-hooks.
Without Nitro: server.interceptors.on('document:beforeInsert', payload => ...) or the server option intercept. A hook that is never registered costs nothing.
Since 2.3:
mongocamp:document:beforeRead | every read of documents (lists, counts, exports, aggregations, schema routes, live updates) and the target of every update, replace and delete. Push conditions to event.scopes (event.scopes.push({ tenant: user.tenant })); they are combined with the client's filter by $and, so it cannot widen them. event.operation tells the kind of request, event.isAdmin and event.withDeleted are set |
instead on beforeDelete | event.instead = { update: { $set: { archived: true } } } turns the delete into this update; the answer stays a delete, the event document:delete carries softDeleted: true |
onNoMatch on beforeReplace / beforeUpdate | called when the write matched nothing, before the 404: throw to explain why (the version check answers 409 this way) |
isAdmin | on every payload: the user has an administrator role |
The behaviours of declared collections are built on these hooks. The interceptors run in stages: guard (what clients may not write) → change (default) → the hooks of the host (Nitro) → validate (the schema) → system (fields the server writes).
Event payload
Every event has id, eventDate and name. Events caused by a user carry user (UserInformation: userId, roles, ...).
Event list
| Event | Payload (besides user) |
|---|---|
server:started | — |
http:requestStart | requestId, httpMethod, methodName (operationId), uri, remoteAddress, userId, ... |
http:requestCompleted | the same plus durationMillis, responseCode |
config:update | key, newValue, oldValue, callingMethod (no user) |
user:login, user:logout | — |
user:create | createdUser |
user:delete | deletedUser |
user:updatePassword, user:updateApiKey | changedUserId |
user:updateRoles | changedUserId, userRoles |
role:create | role |
role:update | role, updateRoleRequest |
role:delete | deletedRole |
database:drop | databaseName |
collection:create, collection:drop, collection:clear, collection:modify | collectionName |
collection:rename, collection:copy | collectionName, newCollectionName |
document:create | collectionName, insertResponse |
document:update | collectionName, updateResponse, oldValues |
document:delete | collectionName, deleteResponse, oldValues |
bucket:drop, bucket:clear | bucketName |
file:create | bucketName, insertResponse |
file:update | bucketName, updateResponse |
file:delete | bucketName, deleteResponse |
job:create | jobConfig |
job:update | jobName, jobGroup, jobConfig |
job:delete | jobName, jobGroup |
document:restore | collectionName, updateResponse, oldValues (2.3) |
job:executed | jobName, jobGroup, className, durationMillis, error? (no user) |
A listener can be limited to collections: server.events.on('document:update', listener, { collections: name => name === 'orders' }) — then old values are read for these collections only.
The types are exported as MongocampEvents, MongocampEvent<'document:update'>, WriteInterceptorPayloads (the before-hooks) and MongocampHooks (the Nitro hooks) from @sfxcode/mongocamp-server-core.
Scope
Events are delivered within the process that handled the request. With several instances, each one sees only its own events. Use a message broker or MongoDB change streams if you need events across instances.
