Skip to main content

Routing

In frourio, controllers are defined using file-system based API routing, similar to Next.js. Definition methods can be broadly classified into controller-level and directory-level, depending on the scope of the effect.

The level used to define each controller element is different, but some elements can be defined at both levels. The following table summarizes them.

ElementsController-levelDirectory-level
HandlerSupported
HooksSupportedSupported
ValidatorsRestricted Only body, headers and queryRestricted Only params
SchemasSupported

Controller-level

If the element is defined at controller-level, it affects only the current endpoint.

Difinition Method : defineController() in controller.ts

caution

defineHooks() and defineResponseSchema() are deprecated after frourio and frourio-express version 0.31.0.

controller.ts
import { defineController } from './$relay';

export default defineController(() => ({
get: () => ({ status: 200, body: 'Hello' }),
post: {
validators: {
query: z.object({ ... }),
body: z.object({ ... }),
},
schemas: {
response: { 201: { type: 'object', properties: { ... } } },
},
hooks: {
preValidation: [],
preHandler: (req, _, done) => { ...; done(); },
},
handler: ({ body }) => ({ status: 201, body: { ... } }),
},
}));

Function defineController()

Argument Type

Return Type

  • object ServerMethods

Object ServerMethodHandler

{
  validators?: (Controller-level Validators),
  schemas?: { response?: { [(HTTP Status Code)]: Schema } },
  hooks?: ServerHooks,
  handler: ServerHandler or ServerHandlerPromise,
}

validators, schemas and hooks can be omitted. If only handler is defined, ServerHandler or ServerHandlerPromise can be passed directly instead of the object.

Directory-level Hooks

If the element is defined at directory-level, it affects the current endpoint and the endpoints under it.

Difinition Method : defineHooks() in hooks.ts

hooks.ts
import { defineHooks } from './$relay';

export default defineHooks(() => ({
onRequest: (req, _, done) => {
console.log(req.url);
done();
},
}));

Function defineHooks()

Argument Type
  • function (fastify: FastifyInstance) => ServerHooks
    • Hooks : An object having the hooks name as keys and the handler functions (or its array) as values.
Return Type
  • object ServerHooks

Directory-level Validators

Difinition Method : defineValidators() in validators.ts

validators.ts
import { defineValidators } from './$relay';
import { z } from 'zod';

export default defineValidators(() => ({
params: z.object({ id: z.string() }),
}));

See the Zod page for more information on defineValidators().