Client Composables
All composables are auto-imported. They work during SSR and in the browser, and they authenticate with the session token of useMongocampAuth().
useMongocampApi()
The generated OpenAPI client: one instance per API group, sharing a configuration (base URL, token, 401 handling).
const {
adminApi, applicationApi, authApi, bucketApi, collectionApi, databaseApi,
documentApi, fileApi, indexApi, systemApi, jobApi,
} = useMongocampApi()
const books = await documentApi.listDocuments({ collectionName: 'books', filter: 'author:Tolkien', rowsPerPage: 50 })Every operation of the REST API is a method here. The composables below are shortcuts for common tasks.
Embedded server during SSR
With the embedded server the URL is relative (/api/mongocamp-server). During SSR these calls go through Nuxt's request fetch and are answered in-process without an HTTP round trip.
The client outside the composables
@sfxcode/nuxt-mongocamp-server/client (2.6) exports the generated client with two helpers, for a proxy, a script or another module:
import { Configuration, createMongocampApis } from '@sfxcode/nuxt-mongocamp-server/client'
const { documentApi, fileApi } = createMongocampApis(
new Configuration({ basePath: 'https://data.example.com', accessToken: token }),
{ keepLongs: true },
)keepLongs keeps integers beyond 2^53 exact: the API writes a Long as a plain JSON number, which JSON.parse rounds, so such a number arrives as { $numberLong: "…" } (canonical Extended JSON). The same is available as keepLongsMiddleware for your own Configuration and as parseJsonKeepingLongs(text) for a raw answer.
The 11 APIs of one createMongocampApis call (and of useMongocampApi()) share one middleware list. Middleware for all of them goes into the middleware option or — later, also for useMongocampApi() — addMongocampMiddleware(apis, ...middleware) (3.1.0, auto-imported in the app; it returns a function that removes it again). Both run before the built-in error conversion, so a post sees the raw error answer:
const rewrite401 = { post: async ({ response }) => response.status === 401 ? new Response(response.body, { status: 403, headers: response.headers }) : response }
addMongocampMiddleware(useMongocampApi(), rewrite401)api.withMiddleware(...) of the generated client still answers a copy of one API with its own list (3.0.0 used it internally, so middleware added to one API's list reached only that API; 3.1.0 shares the list again as 2.x did).
The api key call is adminApi.generateNewApiKeyForUser (since 2.6; 3.0 removed the misspelled alias gnerateNewApiKeyForUser).
Search
useMongocampSearch()
const { find, findAll, findByField, mongoFindRequest, findRequest } = useMongocampSearch()
await find('books', 'year:[1950 TO 1960]', 1, ['-year'], ['title', 'year'], 20)
await find('books', 'title:hobb*', 1, undefined, undefined, 20, true) // filterCaseInsensitive
await findAll('books', 2) // page 2 without a filter
await findByField('books', 'isbn', '978-0261103573')find(collection, filter, page, sort, projection, rowsPerPage, filterCaseInsensitive): the filter is a Lucene query. Sort fields with a leading - sort descending. Wildcards match case-sensitively unless filterCaseInsensitive is true.
usePaginatedFind(collection, options)
Reactive paging around find:
const { documents, page, rowsPerPage, pending, error, load, nextPage, previousPage, goToPage } = usePaginatedFind('books', {
filter: 'genre:fantasy',
sort: ['title'],
projection: ['title', 'author'],
rowsPerPage: 25,
filterCaseInsensitive: false,
})
await load()
await nextPage()The documents come as the server sends them (relaxed Extended JSON). usePaginatedFind<Book>('books') types them; for decoded documents use useMongocampCollection.
Typed collections
useMongocampCollection(name)
Since 2.3. For a declared collection the documents are typed by its schema; the documents are decoded from Extended JSON (ObjectId, Date, Decimal128 as values) and encoded for the requests:
// server/mongocamp/orders.ts declares the collection orders
const orders = useMongocampCollection('orders')
const open = await orders.find({ filter: 'status:open', sort: ['-createdAt'], rowsPerPage: 20 }) // Order[]
open[0].createdAt.getFullYear() // a Date
const { documents, countRows, countPages } = await orders.findPage({ page: 2 })
const one = await orders.findById(open[0]._id) // Order | null (null for 404)
await orders.insert({ customer: 'Ada', createdAt: new Date() }) // the input type: qty and status have defaults
await orders.update(one!._id, { status: 'done' }) // Partial<Order>, sent as $set
await orders.replace(one!._id, { customer: 'Ada', qty: 2, createdAt: new Date() })
await orders.remove(one!._id)Ids can be given as text, ObjectId or a document with _id. Reads are typed with the stored type of the schema (its output), insert and replace with the type before defaults (its input).
For other collections pass a type, or get plain records:
const notes = useMongocampCollection<{ text: string }>('notes')
const anything = useMongocampCollection('logs') // Record<string, unknown>Reactive paging, with the counts of the server:
const { documents, page, countRows, pending, error, load, nextPage } = orders.paginated({ filter: 'status:open', rowsPerPage: 25 })
await load()A failed request throws a MongocampRequestError: an Error with status, message, additionalInfo, code and, for a document that is not valid, issues (one per field, for forms). Since 3.0 it is a class (also a ResponseError of the generated client), and every client call throws it, the useMongocampApi* wrappers and paginated() too; isMongocampError(e) narrows:
import type { MongocampRequestError } from '@sfxcode/nuxt-mongocamp-server'
try {
await orders.insert({ customer: '', createdAt: new Date() })
}
catch (e) {
for (const issue of (e as MongocampRequestError).issues ?? []) {
console.log(issue.path, issue.message) // customer Too small: expected string to have >=1 characters
}
}Versions and conflicts
For collections with behaviours the composable learns them from the server once (GET …/declaration) and does the right thing:
const order = await orders.findById(id)
await orders.update(order!, { status: 'done' }) // sends the version of order: a change of someone else in between answers 409
await orders.update(id, { status: 'done' }) // only an id: last write wins
await orders.update(order!, { status: 'done' }, { retryOnConflict: true }) // on 409 once more, on the stored versiontry {
await orders.update(order!, { status: 'done' })
}
catch (e) {
const error = e as MongocampRequestError
if (error.isConflict) {
showBoth(order, error.current) // the stored document, decoded
}
}The fields the server writes (timestamps, owner, version, deleted mark) and protected fields are left out of what is sent, so a document that was read can be sent back as it is.
await orders.restore(id) // softDelete
await orders.find({ withDeleted: true }) // administrators of the collection
const entries = await orders.history(id) // audit: [{ operation, user, at, before, after }]
orders.isMine(order) // owner: for edit buttons (reactive)Expanding references
For a collection with refs (2.4) a read can bring the referenced documents along:
const orders = useMongocampCollection('orders')
const list = await orders.find({ filter: 'status:open', expand: ['customerId'] })
list[0].customerId?.name // the customers document | null, typed
const one = await orders.findById(id, { expand: ['customerId', 'tagIds'] })
const { documents } = orders.paginated({ expand: ['customerId'] })Only declared references can be expanded (TypeScript knows the names). A reference you cannot read is null, or left out of an array. Writing back sends the ids again; replace refuses a document read with expand whose reference is null or an array (you might not see all of it), update sends only what you change.
useMongocampLive(name, options)
A live list in one line (2.3):
const { documents, status, error, stop, reload } = useMongocampLive('orders', { filter: 'status:open' })expand works here too (2.4): the first load and every changed document come with the referenced documents. A change of a referenced document (the customer) does not update the list.
The documents are loaded typed and decoded and kept in sync with the live updates of the server: an inserted or changed order appears, one that no longer matches the filter or is deleted goes. With sort or page every change loads the page again (mode: 'refetch'), else the list is patched. A lost connection is opened again and resumes where it stopped. Without a replica set the server cannot stream: status is polling and the list is loaded every pollInterval (default 5 s). In a component it starts when mounted and stops when unmounted; immediate: false and start() for other places.
With an external server, the module types collections only when server.collectionsDir is set. You can also declare the types yourself:
declare global {
interface MongocampCollections { orders: Order }
}Collections and databases
useMongocampApiCollection(name)
const books = useMongocampApiCollection('books')
await books.insert({ title: 'The Hobbit', year: 1937 })
await books.insertMany([{ title: 'A' }, { title: 'B' }])
await books.replace(id, { title: 'The Hobbit', year: 1937 }) // the whole document (3.0; `update` does the same)
await books.patch(id, { year: 1938 }) // these fields only (3.0; `updatePartial` does the same)
await books.remove(id)
await books.removeMany({ year: { $lt: 1900 } })
await books.aggregate({ pipeline: [{ stage: 'group', value: { _id: '$author', n: { $sum: 1 } } }] })
await books.information(true) // counts, sizes, details
await books.schemaAnalysis()
await books.distinct('author')
await books.clear()useMongocampApiCollections()
list(), listByDatabase(db), listDatabases(), databaseInfo(db), databaseInfos(), deleteDatabase(db).
Collections in other databases are addressed as database:collection (e.g. geodata:locations) in every collection route.
Files
useMongocampApiFiles()
GridFS buckets and files: listBuckets(), getBucket(name), clearBucket(name), deleteBucket(name), list(bucket, filter?, sort?, projection?, rowsPerPage?, page?), find(bucket, mongoFindRequest, rowsPerPage?, page?), (Lucene search: fileApi.searchFiles({ bucketName, searchRequest: { filter } }), 2.6), info(bucket, id), download(bucket, id), upload(bucket, blob, metaData, fileName?), update(bucket, id, request), remove(bucket, id).
useMongocampBucket(name)
The files of a bucket with the metadata type of its declaration (2.11): list, info, upload(file, { fileName, metadata }), update, remove, and link(id, { expiresIn, variant }) — a signed URL for <img src>. fileLink(bucket, id, options) answers such a URL for any bucket.
const avatars = useMongocampBucket('avatars')
const { insertedIds } = await avatars.upload(file, { metadata: { alt: 'Me' } })
const src = await avatars.link(insertedIds![0]!, { expiresIn: '1h', variant: { w: 320, format: 'webp' } })Jobs
useMongocampApiJobs()
list(), listAvailable() (the handler classes), register(config), update(group, name, config), remove(group, name), execute(group, name). See Jobs.
Administration
useMongocampApiAdmin()
Users: listUsers, getUser, addUser, deleteUser, updatePasswordForUser, updateRolesForUser, generateNewApiKeyForUser. Roles: listRoles, getRole, addRole, updateRole, deleteRole.
Session and configuration
| Composable | Purpose |
|---|---|
useMongocampAuth() | Login, logout, isLoggedIn, userRoles, userGrants, token refresh; 3.0: register, verifyEmail, requestPasswordReset, resetPassword, requestLoginLink, loginWithLink, sessions, revokeSession, revokeAllSessions. See Authentication. |
useMongocampUser() | The current user profile (read-only). |
useMongocampStorage() | The session cookie { token, profile }. |
useMongocampUrl() | The configured base URL. |
Errors
The generated client rejects with a ResponseError for every status ≥ 400. Since 3.0 the clients of the module and of createMongocampApis reject with a MongocampRequestError, a subclass with the answer already read (status, message, code, issues, isConflict, current), so this code keeps working and new code can use one type. The server describes the error in headers and body:
import { ResponseError } from '@sfxcode/nuxt-mongocamp-server/api'
try {
await documentApi.getDocument({ collectionName: 'books', documentId: 'missing' })
}
catch (e) {
if (e instanceof ResponseError) {
e.response.status // 404
e.response.headers.get('x-error-code')
e.response.headers.get('x-error-message')
}
}See Errors for the codes. useMongocampCollection throws errors with status, message and issues already read.
