fastify-type-provider-valibot
TypeScript icon, indicating that this package has built-in type declarations

1.0.9 • Public • Published

Fastify Type Provider Valibot

NPM Version NPM Downloads Build Status

How to use?

pnpm install fastify-type-provider-valibot valibot
import Fastify from "fastify";
import { serializerCompiler, validatorCompiler, ValibotTypeProvider } from "fastify-type-provider-valibot";
import * as v from "valibot";

const app = Fastify()

// Add schema validator and serializer
app.setSerializerCompiler(serializerCompiler);

//validatorCompiler(ajvInstance?, fallbackFunction?)
//First Argument : You can pass an AJV Instance to validate schema by AJV
//Second Argument : 
//You can precise a function to handle the case where schema is not from Valibot.
//The function should respect :  (schema: unknown, data: unknown) => FastifyValidationResult
app.setValidatorCompiler(validatorCompiler()); 

app.withTypeProvider<ValibotTypeProvider>().route({
  method: "GET",
  url: "/",
  // Define your schema
  schema: {
    querystring: v.object({
      name: v.string(),
    }),
    response: {
      200: v.undefined_('test'),
    },
  },
  handler: (req, res) => {
    res.send(req.query.name);
  },
});

app.listen({ port: 4949 });

How to use together with @fastify/swagger

import fastify from 'fastify';
import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUI from '@fastify/swagger-ui';
import * as v from 'valibot';

import {
  jsonSchemaTransform,
  createJsonSchemaTransform,
  serializerCompiler,
  validatorCompiler,
  ValibotTypeProvider,
} from 'fastify-type-provider-valibot';

const app = fastify();
app.setValidatorCompiler(validatorCompiler());
app.setSerializerCompiler(serializerCompiler);

app.register(fastifySwagger, {
  openapi: {
    info: {
      title: 'SampleApi',
      description: 'Sample backend service',
      version: '1.0.0',
    },
    servers: [],
  },
  transform: jsonSchemaTransform,
  // You can also create transform with custom skiplist of endpoints that should not be included in the specification:
  //
  // transform: createJsonSchemaTransform({
  //   skipList: [ '/documentation/static/*' ]
  // })
});

app.register(fastifySwaggerUI, {
  routePrefix: '/documentation',
});

const LOGIN_SCHEMA = v.object({
  username: v.string(),
  password: v.string(),
});

app.after(() => {
  app.withTypeProvider<ValibotTypeProvider>().route({
    method: 'POST',
    url: '/login',
    schema: { body: LOGIN_SCHEMA },
    handler: (req, res) => {
      res.send('ok');
    },
  });
});

async function run() {
  await app.ready();

  await app.listen({
    port: 4949,
  });

  console.log(`Documentation running at http://localhost:4949/documentation`);
}

run();

Package Sidebar

Install

npm i fastify-type-provider-valibot

Weekly Downloads

209

Version

1.0.9

License

MIT

Unpacked Size

45.8 kB

Total Files

28

Last publish

Collaborators

  • qlaffont