Coder Social home page Coder Social logo

fastify-typebox's Introduction

Fastify TypeBox

Enhanced TypeBox support for Fastify

npm version

Install

$ npm install fastify-typebox --save

Overview

This library provides enhanced TypeBox support for Fastify. It enables automatic type inference for Fastify requests with no additional type hinting required. This library achieves this by remapping the Fastify interface using TypeScript conditional types only. It reconstructs Fastify Request and Reply types making them fully TypeBox aware.

IMPORTANT: This project is intended to serve as prototype for exploring various static type inference possibilities in Fastify. It was developed to test TypeScript inference performance and static type checking behaviours. It is not recommended to take this project as a dependency, instead consider the upcoming Type Provider functionality due to release in Fastify version 4.0.

Requires TypeScript 4.3.5 and above.

License MIT

Contents

Usage

The following demonstrates general usage.

import Fastify, { Type } from 'fastify-typebox'

const fastify = Fastify()

fastify.post('/users/:userId', { 
    schema: {
        body: Type.Object({
            x: Type.Number(),
            y: Type.Number()
        }),
        response: {
            200: Type.Object({
                result: Type.Number()
            })
        }
    }
}, (request, reply) => {
    
    // -------------------------------------
    // Requests
    // -------------------------------------

    // type Params = { userId: string }

    const { userId } = request.params

    // type Body = { x: number, y: number }

    const { x, y } = request.body             

    // -------------------------------------
    // Replies
    // -------------------------------------

    // type Response = { 200: { result: number } }

    reply.send({ result: 100 })                // error: no status code specified

    reply.status(400).send({ result: 42 })     // error: 400 status code not defined

    reply.status(200).send({ result: '42' })   // error: result type is not number

    reply.status(200).send({ result: x + y  })  // ok: !
})

Request

Request handling should work inline with Fastify, However you must supply schemas as TypeBox types. Fastify TypeBox will then automatically infer the correct types in the Fastify route handlers. Request hooks are not supported.

fastify.get('/records', {
    schema: {
        querystring: Type.Object({
            offset: Type.Integer({ minimum: 0 }),
            limit: Type.Integer({ maximum: 64 }),
        }),
        response: {
            200: Type.Array(
                Type.Object({
                    id: Type.String({format: 'uuid' }),
                    email: Type.String({format: 'email' })
                })
            )
        }
    }
}, async (request, reply) => {
    const { offset, limit } = request.query
    const records = await get(offset, limit)
    reply.status(200).send(records)
})

Params

Fastify TypeBox supports automatic param inference from urls. Param properties are always inferred as strings.

fastify.get('/users/:userId', (request, reply) => {
    const { userId } = request.params // userId is string
})

Reply

Fastify TypeBox implements static type checking which is derived from the status codes specified for a route. Users must call status(...) prior to calling send(...) where the specified status code is used to select the appropriate response schema.

fastify.get('/action', {
    schema: {
        response: {
            200: Type.String(),
            401: Type.Boolean(),
            500: Type.Number(),
        }
    }
}, (request, reply) => {
    reply.status(200).send('ok')  // must be string
    reply.status(401).send(false) // must be boolean
    reply.status(500).send(42)    // must be number
})

Plugins

Fastify TypeBox provides mappings for Fastify plugins. To enable type inference for the plugin, specify FastifyTypeBoxInstance instead of FastifyInstance for the instance parameter type.

import { FastifyTypeBoxInstance } from 'fastify-typebox'

async function MyPlugin(instance: FastifyTypeBoxInstance, options: { config: any }) {

    instance.get('/hello', (request, reply) => reply.send('world'))
}

...

fastify.register(MyPlugin, { config: 'xyz' })

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.