Skip to content

9. Server code ​

The shop gets a checkout: one request that finds the customer by email (or creates it) and places the order. That is a Nitro route, and useMongocampServerCollection gives it the same collections with the same rules as the API:

ts
import { toErrorResponse } from '@sfxcode/mongocamp-server-core'
import { ObjectId } from 'mongodb'
import { defineHandler } from 'nitro'
import { readBody } from 'nitro/h3'

interface PlaceOrder {
  name: string
  email: string
  items: Array<{ product: string, qty: number, price: number }>
}

/** Places an order for a customer by email: the customer is created on the first order. */
export default defineHandler(async (event) => {
  try {
    const { name, email, items } = await readBody<PlaceOrder>(event) ?? { name: '', email: '', items: [] }
    // the caller of the request: its grants, the owner rules, validation, timestamps, audit and the hooks apply
    const customers = useMongocampServerCollection('customers', { user: event })
    const orders = useMongocampServerCollection('orders', { user: event })
    const [known] = await customers.find({ filter: { email }, rowsPerPage: 1 })
    const customerId = known?._id ?? (await customers.insert({ name, email })).insertedIds?.[0]
    return await orders.insert({ customerId: new ObjectId(String(customerId)), items, status: 'open' })
  }
  catch (error) {
    // 400 with issues, 403, 409, ... as the API answers them
    return toErrorResponse(error)
  }
})
  • { user: event } acts as the caller of the request, with its token, grants and owner rules. createdBy is the caller, the before-hook computes the total, the schema validates, and the audit records the order.
  • { user: 'system' } acts as an administrator without owner rules, for seeds, jobs and plugins. A user id ('ann') acts as that user.
  • The documents are driver values (ObjectId, Date), typed by the declaration like on the client.
  • Errors: a MongocampError that leaves a route would be a 500. toErrorResponse answers it like the API (400 with issues, 404, 409, …), so the client sees the same errors as from the API.

Call it from the page with the token of the session:

ts
await $fetch('/api/orders', {
  method: 'POST',
  headers: { authorization: `Bearer ${useMongocampStorage().value.token}` },
  body: { name: 'Grace', email: 'grace@example.com', items: [{ product: 'pen', qty: 3, price: 2 }] },
})

When to use the driver instead ​

(await useMongocampCore()).context.database.db() is the plain MongoDB Db. It bypasses every rule: no grants, no validation, no behaviours, no hooks. Use it for migrations, bulk repairs and reports over all data, never for work done on behalf of a user.

Imports in Nitro code

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

Released under the MIT License.