Skip to main content

Controller

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

export default defineController(() => ({
get: () => ({ status: 200, body: 'Hello' }),
post: async ({ query: { foo }, params: { bar }, body }) => {
const baz = await createBaz(foo, bar, body);
if (!baz) return { status: 400 };
return { status: 201, body: baz };
},
}));

To define controllers, use the function defineMethods exported by ./$relay.ts.

The type definition of defineController is automatically generated based on the aspida type definition. It must be imported from $relay.ts in the same directory as the controller.

The return value of defineController must be default exported.

If you want to use the fastify instance in the controller, you can take it as an argument.

Function defineController

Argument Type

Return Type

  • object ServerMethods

Object ServerMethodHandler

$server.ts (formatted)
export type ServerMethodHandler<T extends AspidaMethodParams, U extends Record<string, any> = {}> =
| ServerHandler<T, U>
| ServerHandlerPromise<T, U>
| {
validators?: Partial<{ [Key in keyof RequestParams<T>]?: z.ZodType<RequestParams<T>[Key]> }>;
handler: ServerHandler<T, U> | ServerHandlerPromise<T, U>;
};

Function ServerHandler

Argument Type

  • object RequestParams & AdditinalRequest
    • query : query
    • headers : reqHeaders
    • params : URL Params
    • body : reqBody

Return Type

  • object ServerResponse | promise Promise<ServerResponse>
    • status : status
    • body : resBody
    • headers : resHeaders

The types of RequestParams and ServerResponse are determined by API type definitions.

If this is included in a Promise using async, it becomes the ServerHandlerPromise.