Skip to content

Server Composables ​

These are auto-imported in the server code of your application (server/api, server/routes, server/plugins, ...).

useMongocampEventApi(event, token?) ​

The generated client for server code. It authenticates with the module's apiKey. Without a key, it uses token (e.g. the token of the current request).

Since 2.8: useMongocampEventApi

Before 2.8 this composable was called useMongocampApi(event) — the name of the browser composable useMongocampApi(). An editor or a type check over the whole project (the root .nuxt/tsconfig.json includes server/**, but only the browser declaration) then resolved the browser one. 3.0 removed the old server name. Type-check server code with .nuxt/tsconfig.server.json (Nuxt 4's project references) to get the server declarations.

The api key wins

With an apiKey in the module options every call runs with the rights of the key's user, also when you pass the token of the request; in development a warning says so once. For calls with the rights of the caller use useMongocampServerCollection(name, { user: event }), or a module without apiKey.

ts
// server/api/mongocamp/users.ts
import { defineHandler } from 'nitro'

export default defineHandler((event) => {
  const { adminApi } = useMongocampEventApi(event)
  return adminApi.listUsers()
})

With the embedded server the calls are answered in-process by the core, so no HTTP request leaves the process. With an external server they go to url.

useMongocampServerApi(url, key?, token?) ​

The lower-level factory when you need another URL or credential:

ts
const { documentApi } = useMongocampServerApi('https://mongocamp.example.com', process.env.OTHER_API_KEY)

useMongocampServerCollection(name, { user }) ​

Since 2.4. The documents of a collection in server code, typed like useMongocampCollection and with the same rules as the API: grants, the read scope (owner, soft delete, your hooks), validation, the behaviours (timestamps, owner, version, audit) and the events. Only with the embedded server.

ts
// server/api/orders/[id]/close.post.ts
import { defineHandler } from 'nitro'
import { getRouterParam, HTTPError } from 'nitro/h3'

export default defineHandler(async (event) => {
  const orders = useMongocampServerCollection('orders', { user: event })  // the caller of the request
  const order = await orders.findById(getRouterParam(event, 'id')!)
  if (!order) {
    throw new HTTPError({ status: 404, message: 'no such order' })
  }
  await orders.update(order, { status: 'done' })  // version checked: 409 when someone changed it in between
  return orders.findById(order, { expand: ['customerId'] })
})

user decides whose rights apply:

userActs as
the eventthe caller of the request (its token, API key or basic auth); 401 without credentials
a user id ('ops')that user with its roles
an AuthorizedUserthat user
'system'an administrator: every grant, no owner rule. For jobs, seeds and plugins.

keepTimestamps: true (2.8.0) makes updates and replaces keep the updatedAt / updatedBy they send, on collections with timestamps.preserveOnUpdate and for administrators (or 'system') — maintenance writes of jobs and scripts: useMongocampServerCollection('notes', { user: 'system', keepTimestamps: true }).

Method
find(options), findPage(options)filter as object ({ status: 'open' }) or Lucene text, sort ({ qty: -1 } or ['-qty']), projection, page, rowsPerPage, withDeleted, expand
findById(id, { expand })the document or null (also when it is not in the scope of the user)
count(filter)
insert(document), insertMany(documents, { ordered })
replace(target, document), update(target, changes)given the document that was read, its version is checked; null in changes removes a field
updateMany(filter, changes), remove(target), removeMany(filter), restore(target)
history(target)the audit records, newest first

Documents come and go as driver values (ObjectId, Date), numbers as JavaScript numbers. Errors are MongocampErrors with status, issues (invalid documents) and current (version conflicts).

Errors in server routes ​

A MongocampError that leaves a Nitro route is an unexpected error for Nitro: the client gets 500. Answer it like the API does with toErrorResponse, so the client composables see the status, the message and the issues:

ts
// server/api/orders.post.ts
import { toErrorResponse } from '@sfxcode/mongocamp-server-core'
import { defineHandler } from 'nitro'
import { readBody } from 'nitro/h3'

export default defineHandler(async (event) => {
  try {
    const orders = useMongocampServerCollection('orders', { user: event })
    return await orders.insert(await readBody(event))
  }
  catch (error) {
    return toErrorResponse(error)  // 400 with issues, 403, 404, 409 with current, ...; other errors: 500 without internals
  }
})

Imports in Nitro code

defineHandler and definePlugin come from nitro, the h3 helpers (readBody, getRouterParam, HTTPError, ...) from nitro/h3.

With your own host the same is server.collection('orders', { user }) of @sfxcode/mongocamp-server-core.

Use the driver ((await useMongocampCore()).context.database) for work that must not go through the rules: migrations, bulk fixes, reports over all data.

useMongocampCore() ​

Only with server.enabled. Resolves to the embedded server instance (MongocampServer of @sfxcode/mongocamp-server-core):

ts
interface MongocampServer {
  fetch: (request: Request) => Promise<Response> // the whole API
  events: EventBus // typed events, see Extensions → Events
  context: MongocampContext // configuration, database, auth holder, scheduler
  registerJobHandler: (className: string, handler: JobHandler) => () => void // see Extensions → Jobs
  use: (feature: MongocampFeature) => Promise<void> // requestLogging(), metrics()
  collection: (name: string, options: { user }) => ServerCollection // 2.4, see useMongocampServerCollection
  routes: () => string[]
  close: () => Promise<void>
}

Use it in server routes and utilities. For startup work and events, write a Nitro plugin on the mongocamp:* hooks instead; it gets the same server on mongocamp:ready:

ts
// server/plugins/seed-admin.ts
import { definePlugin } from 'nitro'

export default definePlugin((nitroApp) => {
  nitroApp.hooks.hook('mongocamp:ready', async (server) => {
    const holder = server.context.auth.mongoHolder // undefined with AUTH_HANDLER=static
    if (holder && !(await holder.findUserOption('ops'))) {
      await holder.addUser({ userId: 'ops', password: process.env.OPS_PASSWORD!, apiKey: null, roles: ['adminRole'] })
    }
  })
  nitroApp.hooks.hook('mongocamp:document:delete', (event) => {
    console.info(event.user.userId, event.collectionName, event.oldValues)
  })
})

context gives direct access when the REST API is not enough (configuration, database, auth holder, scheduler).

WARNING

useMongocampCore() rejects when the embedded server is not enabled. The server is created once per Nitro instance, on the first call or request, and closed when Nitro stops.

Released under the MIT License.