Skip to content

Custom Routes ​

The core does not need to know about your routes. Put them next to it.

In a Nuxt app ​

The embedded API lives under its prefix (/api/mongocamp-server/**). Everything else in server/ is yours, and the server composables give you the API:

ts
// server/api/books/top.get.ts
import { defineHandler } from 'nitro'

export default defineHandler(async (event) => {
  const { collectionApi } = useMongocampApi(event)
  return collectionApi.aggregate({
    collectionName: 'books',
    mongoAggregateRequest: {
      pipeline: [
        { stage: 'sort', value: { rating: -1 } },
        { stage: 'limit', value: 10 },
      ],
    },
  })
})

For direct database access in a route, use (await useMongocampCore()).context.database.db() (a MongoDB Db; pass a name for another database).

In your own host ​

Answer your own paths first and give every other request to server.fetch:

ts
import { createMongocampServer } from '@sfxcode/mongocamp-server-core'

const mongocamp = await createMongocampServer()

export default {
  async fetch(request: Request) {
    if (new URL(request.url).pathname === '/report')
      return Response.json(await buildReport())
    return mongocamp.fetch(request)
  },
}

In Nitro 3 a route file (routes/report.get.ts) or a middleware does the same. apps/server/server.ts is a complete example of a host.

Released under the MIT License.