Skip to content

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):

ts
// 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:

ts
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() // unsubscribe

server.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:

ts
// 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')
    }
  })
})
HookPayload (besides user, collectionName, databaseName)Routes
mongocamp:document:beforeInsertdocuments, source (insert, insertMany, import), lines (import)insert, insert many, import (once per batch of 1000 lines)
mongocamp:document:beforeReplacefilter, documentPATCH …/documents/{id}
mongocamp:document:beforeUpdatefilter, update (the operators), manyPATCH …/{id}/partial, many/update
mongocamp:document:beforeDeletefilter, manyDELETE …/{id}, many/delete
  • They run after the authorization and the decoding of the body; the values are driver values (ObjectId, Date, whole numbers as Long).
  • Change the write in place on the payload (event.filter = { ...event.filter, tenant }).
  • Refuse it by throwing: a MongocampError is answered with its status (MongocampError.validation(issues) for invalid documents, see Errors), any other error with 500. 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:beforeReadevery 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 beforeDeleteevent.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 / beforeUpdatecalled when the write matched nothing, before the 404: throw to explain why (the version check answers 409 this way)
isAdminon 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 ​

EventPayload (besides user)
server:started—
http:requestStartrequestId, httpMethod, methodName (operationId), uri, remoteAddress, userId, ...
http:requestCompletedthe same plus durationMillis, responseCode
config:updatekey, newValue, oldValue, callingMethod (no user)
user:login, user:logout—
user:createcreatedUser
user:deletedeletedUser
user:updatePassword, user:updateApiKeychangedUserId
user:updateRoleschangedUserId, userRoles
role:createrole
role:updaterole, updateRoleRequest
role:deletedeletedRole
database:dropdatabaseName
collection:create, collection:drop, collection:clear, collection:modifycollectionName
collection:rename, collection:copycollectionName, newCollectionName
document:createcollectionName, insertResponse
document:updatecollectionName, updateResponse, oldValues
document:deletecollectionName, deleteResponse, oldValues
bucket:drop, bucket:clearbucketName
file:createbucketName, insertResponse
file:updatebucketName, updateResponse
file:deletebucketName, deleteResponse
job:createjobConfig
job:updatejobName, jobGroup, jobConfig
job:deletejobName, jobGroup
document:restorecollectionName, updateResponse, oldValues (2.3)
job:executedjobName, 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.

Released under the MIT License.