typescriptjsonschemafastify

How to convert TypeScript Interfaces and Types to JSON for Fastify Interoperability


I am new to Fastify and I do not want to write JSON schema objects from scratch, but leverage TypeScript Interfaces and Types exposed from an existing Data Access Controller. How can I convert those TS Interfaces/Types into JSON schemas, either at dev-time or runtime, for consumption by Fastify to better support RESTful API validation? Thank you in advance.


Solution

  • According to the Fastify documentation you can achieve what you want by using type providers.

    In the example below I used the Typebox to generate the TypeScript type and JSON schema-compatible Object to use in the runtime

    import Fastify, { type RequestGenericInterface } from "fastify";
    import { type TypeBoxTypeProvider } from "@fastify/type-provider-typebox";
    import { type Static, Type } from "@sinclair/typebox";
    
    const UserSchema = Type.Object({ username: Type.Optional(Type.String()) });
    
    type UserType = Static<typeof UserSchema>;
    
    const app = Fastify().withTypeProvider<TypeBoxTypeProvider>();
    
    interface RequestPayloadType extends RequestGenericInterface {
      Querystring: UserType;
    }
    
    app.get<RequestPayloadType>(
      "/user",
      { schema: { querystring: UserSchema } },
      (req, _) => {
        const result = req.query.username ?? "no-name";
        return result;
      }
    );