Giter Site home page Giter Site logo

fastify-type-provider-typebox's Introduction

fastify-type-provider-typebox

A Type Provider for Typebox

Installation

npm i @sinclair/typebox # Required as peer dependency
npm i @fastify/type-provider-typebox

Overview

This package provides enhanced support for TypeBox by integrating it with the Fastify Type Provider infrastructure. It provides a re-export of the TypeBox Type.* builder for convenience as well as providing additional utility types and optional validation infrastructure that can be useful when leveraging TypeBox with Fastify.

Usage

import Fastify from 'fastify'
import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox'

const fastify = Fastify().withTypeProvider<TypeBoxTypeProvider>()

Note that the following will not work:

import Fastify from 'fastify'
import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox'

const fastify = Fastify()

fastify.withTypeProvider<TypeBoxTypeProvider>()

Example

import Fastify from 'fastify'
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'

// This package re-export Typebox package
// but you can also use any builders imported 
// directly from @sinclair/typebox
import { Type } from '@sinclair/typebox'


const fastify = Fastify().withTypeProvider<TypeBoxTypeProvider>()

fastify.post('/', {
  schema: {
    body: Type.Object({
      x: Type.String(),
      y: Type.Number(),
      z: Type.Boolean()
    })
  }
}, (req) => {
  // The `x`, `y`, `z` types are automatically inferred
  const { x, y, z } = req.body
})

Type definition of FastifyRequest & FastifyReply + TypeProvider

import {
  FastifyReply,
  FastifyRequest,
  RawRequestDefaultExpression,
  RawServerDefault,
  RawReplyDefaultExpression,
  ContextConfigDefault
} from 'fastify';
import { RouteGenericInterface } from 'fastify/types/route';
import { FastifySchema } from 'fastify/types/schema';
import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox';

export type FastifyRequestTypebox<TSchema extends FastifySchema> = FastifyRequest<
  RouteGenericInterface,
  RawServerDefault,
  RawRequestDefaultExpression<RawServerDefault>,
  TSchema,
  TypeBoxTypeProvider
>;

export type FastifyReplyTypebox<TSchema extends FastifySchema> = FastifyReply<
  RawServerDefault,
  RawRequestDefaultExpression,
  RawReplyDefaultExpression,
  RouteGenericInterface,
  ContextConfigDefault,
  TSchema,
  TypeBoxTypeProvider
>

export const CreateProductSchema = {
  body: Type.Object({
    name: Type.String(),
    price: Type.Number(),
  }),
  response: {
    201: Type.Object({
      id: Type.Number(),
    }),
  },
};

export const CreateProductHandler = (
  req: FastifyRequestTypebox<typeof CreateProductSchema>,
  reply: FastifyReplyTypebox<typeof CreateProductSchema>
) => {
  // The `name` and `price` types are automatically inferred
  const { name, price } = req.body;

  // The response body type is automatically inferred
  reply.status(201).send({ id: 'string-value' });
  //                       ^? error TS2322: Type 'string' is not assignable to type 'number'.
};

Plugin definition

Note When using plugin types, withTypeProvider is not required in order to register the plugin

import { Type, FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox'

const plugin: FastifyPluginAsyncTypebox = async function(fastify, _opts) {
  fastify.get('/', {
    schema: {
      body: Type.Object({
        x: Type.String(),
        y: Type.Number(),
        z: Type.Boolean()
      })
    }
  }, (req) => {
    /// The `x`, `y`, and `z` types are automatically inferred
    const { x, y, z } = req.body
  });
}

Type Compiler

TypeBox provides an optional type compiler that perform very fast runtime type checking for data received on routes. Note this compiler is limited to types expressable through the TypeBox Type.* namespace only. To enable this compiler, you can call .setValidatorCompiler(...) with the TypeBoxValidatorCompiler export provided by this package.

import { Type, TypeBoxTypeProvider, TypeBoxValidatorCompiler } from '@fastify/type-provider-typebox'
import Fastify from 'fastify'

const fastify = Fastify().setValidatorCompiler(TypeBoxValidatorCompiler)

fastify.withTypeProvider<TypeBoxTypeProvider>().get('/', {
  schema: {
    querystring: Type.Object({
      x: Type.String(),
      y: Type.String(),
      z: Type.String()
    })
  }
}, (req) => {
  const { x, y, z } = req.query
})

For additional information on this compiler, please refer to the TypeBox documentation located here

fastify-type-provider-typebox's People

Contributors

dependabot[bot] avatar driimus avatar fdawgs avatar hanspagel avatar liam-tait avatar markusgeert avatar mcollina avatar nadhifikbarw avatar p-kuen avatar rafaelgss avatar samialdury avatar semoal avatar simenb avatar sinclairzx81 avatar superkxt avatar trim21 avatar uzlopak avatar vitoladev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-type-provider-typebox's Issues

Type error: TypeBoxTypeProvider does not satisfy the constraint FastifyTypeProvider

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.24.3

Plugin version

3.5.0

Node.js version

18.15.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

Ventura 13.5.1

Description

TypeBoxTypeProvider produces a type error in version 3.5.0. I am not facing this issue in version 3.1.0.

Steps to Reproduce

import Fastify from 'fastify'
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'

const fastify = Fastify().withTypeProvider<TypeBoxTypeProvider>()

This produces a type error:

error TS2344: Type 'TypeBoxTypeProvider' does not satisfy the constraint 'FastifyTypeProvider'.
  Property 'input' is missing in type 'TypeBoxTypeProvider' but required in type 'FastifyTypeProvider'.

Typescript version: 5.0.4

Expected Behavior

No response

Publish updated npm package

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

The Fastify v4 announcement highlights this library https://medium.com/@fastifyjs/fastify-v4-ga-59f2103b5f0e :

import Fastify from 'fastify'
import { TypeBoxTypeProvider, Type } from 'fastify-type-provider-typebox'

const fastify = Fastify({
  ajv: {
    customOptions: {
      strict: 'log',
      keywords: ['kind', 'modifier']
    }
  }
}).withTypeProvider<TypeBoxTypeProvider>()

But it looks like the npm package is out of date and unusable.

npm install @fastify/type-provider-typebox  
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/fastify
npm ERR!   fastify@"^4.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer fastify@"github:fastify/fastify#next" from @fastify/[email protected]
npm ERR! node_modules/@fastify/type-provider-typebox
npm ERR!   @fastify/type-provider-typebox@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

My machine:

$ node --version
v18.2.0
$ npm --version
8.9.0

My package.json:

  "dependencies": {
    "@types/node": "^17.0.41",
    "fastify": "^4.0.0"
  },
  "devDependencies": {
    "typescript": "^4.7.3"
  }

Type.String({ format: "date" }) doesn't work in body validator

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.15.0

Plugin version

3.2.0

Node.js version

18

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

13.3.1

Description

Type.String({ format: "date" }) doesn't work in body schema validator

Validation error in request to: POST /blah/blah
    err: {
      "type": "Error",
      "message": "body/periodStart Unknown string format 'date'",
      "stack":
          Error: body/periodStart Unknown string format 'date'
...
      "statusCode": 400,
      "validation": [
        {
          "message": "Unknown string format 'date'",
          "instancePath": "/periodStart"
        }
      ],
      "validationContext": "body"
    }

This works fine with ajv validator but as soon as I enable TypeBoxValidatorCompiler, It fails to receive request with the error above.

Steps to Reproduce

use Type.String({ format: "date" }) in body schema with TypeBoxValidatorCompiler enabled

Expected Behavior

No response

Mention in Typebox Readme.md under "Ecosystem"

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hey!

This is a generic message asking you if you would like that this package should be mentioned in the future/new "Ecosystem" section inside the typebox repository.

Would be great if you (any maintainer) could simply drop a reponse in sinclairzx81/typebox#435.

Want it to be part of the documentation?

Yes -> Then please comment with the package name and a short description for it, for more info see the issue.
No -> Please simply comment "no thanks - packageNameHere"

Sorry for posting an "issue" for this, I hope it did not bother to much, feel free to close it!

Expose all of typebox

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

I think we should expose all of typebox to remove the need to install typebox separately (and risk potential versions conflicts):

import Fastify from 'fastify'
import { TypeBoxTypeProvider, Type } from '@fastify/type-provider-typebox'

const fastify = Fastify().withTypeProvider<TypeBoxTypeProvider>()

fastify.get('/', {
  schema: {
    body: Type.Object({
      x: Type.String(),
      y: Type.Number(),
      z: Type.Boolean()
    })
  }
}, (req) => {
  // The `x`, `y`, `z` types are automatically inferred
  const { x, y, z } = req.body
})

Motivation

No response

Example

No response

Widen typebox peerDependency to allow 0.26

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

typebox released version 0.26, but the peerDependency constraint prevents properly updating typebox without causing issues with the Fastify integration.

Since typebox is still at 0.x, the ^ version constraint doesn't include minor versions yet.

I'd suggest widening it to ^0.25.9 || ^0.26.0.

Release notes: sinclairzx81/typebox#346

Impossible to declare TypeboxProvider type

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.5.3

Plugin version

2.3.0

Node.js version

14.18.3

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.5

Description

Hello,
I try to add TypeboxProvider to my type FastifyInstance without success. I don't know what I do wrong. Someone can help me please ^^.
Regards
Quentin

Steps to Reproduce

Check repro : https://github.com/qlaffont/fastify-typebox-error-repro

Expected Behavior

No response

Allow providing `references: Types.TSchema[]` to TypeboxCompiler

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Allow providing an array of schema to be used as Refs with TypeboxCompiler
references: Types.TSchema[]

Motivation

you should be able to specify schemas to the compiler as using fastify schema registry is not queried at compile type by TypeboxSchemaCompiler

Example

No response

Does not type check if withTypeProvider is not fluent

Consider the following:

import Fastify from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';

const server = Fastify();

server.withTypeProvider<TypeBoxTypeProvider>();

server.post('/', {
  schema: {
    body: Type.Object({
      name: Type.String()
    })
  }
}, async (request, reply) => {
  const { name } = request.body;
  return { hello: name };
})

server.listen({ port: 3000 })

This does not work but it errors with:

server.ts:16:11 - error TS2339: Property 'name' does not exist on type 'unknown'.

16   const { name } = request.body;
             ~~~~

However if we inline the route definition and withTypeProvider call it works:

import Fastify from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';

const server = Fastify();

server.withTypeProvider<TypeBoxTypeProvider>().post('/', {
  schema: {
    body: Type.Object({
      name: Type.String()
    })
  }
}, async (request) => {
  const { name } = request.body;
  return { hello: name };
})

server.listen({ port: 3000 })

Reply type check improvement

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Hi,

Look at the followng code:

fastify.post(
    "/users/:id",
    {
      schema: {
        body: Type.Object({
          firstName: Type.String({ minLength: 1, maxLength: 9 }),
          lastName: Type.String({ minLength: 1, maxLength: 9 }),
        }),
        response: {
          201: userSchema,
        },
      },
    },
    async (_request, response) => {
      return response.code(201).send({ id: 1, fullName: "" });
    }
  );

Type checking works nice, everything is correct, everyone is happy.

Now imagine changing '.code(' function argument from schema defined 201 to 300 for example. TypeScript will still be happy. Even though we return something not mentioned in the schema. It would be nice if this could be reported as well?

Even worse though, imagine specifying one more code in the response section of the schema. 300 for example, with a different response type.
Now try sending mismatched reply from the handler. Like code 201 with the payload that, according to the schema, belongs to code 300.
Typescript will again be happy.
Now if this could be solved, then that would be even better.

I would love it if the 'send' function could accept code parameter directly so that the type inference could be more rigid and correct in all cases.
Or some other typescript trickery that could still allow for function chaining with more solid type inference.

Perhaps I'm missing something here?

Summary:

  • I would like code/send type mismatch prevention (based on schema)
  • I would also like schema undefined status code prevention

Motivation

Better type inference that could lead to absolutely type safe reply composition.

Example

fastify.post(
    "/users/:id",
    {
      schema: {
        body: Type.Object({
          firstName: Type.String({ minLength: 1, maxLength: 9 }),
          lastName: Type.String({ minLength: 1, maxLength: 9 }),
        }),
        response: {
          201: userSchema,
          300: someOtherSchema,
        },
      },
    },
    async (_request, response) => {
      return response.code(201).send({ id: 1, fullName: "" });
    }
  );

Error `forgotten to call 'done'` since version 3.4

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the regression has not already been reported

Last working version

3.3

Stopped working in version

3.4 (including 3.5)

Node.js version

20.4

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Archlinux / Not applicable

💥 Regression Report

With no code change, this library is now breaking with:

    FastifyError: fastify-plugin: Plugin did not start in time: 'bound _encapsulateThreeParam'. You may have forgotten to call 'done' function or to resolve a Promise

      at manageErr (../../node_modules/fastify/fastify.js:588:33)
      at ../../node_modules/fastify/fastify.js:575:11
      at Object._encapsulateThreeParam (../../node_modules/avvio/boot.js:562:7)
      at Boot.timeoutCall (../../node_modules/avvio/boot.js:458:5)
      at Boot.callWithCbOrNextTick (../../node_modules/avvio/boot.js:440:19)
      at Task.release (../../node_modules/fastq/queue.js:149:16)
      at worked (../../node_modules/fastq/queue.js:201:10)
      at Timeout._onTimeout (../../node_modules/avvio/boot.js:454:5)

The same code works fine in 3.3 (breaks in 3.4 and 3.5)

Steps to Reproduce

import { Type } from "@fastify/type-provider-typebox"
import { FastifyPluginCallback, FastifyPluginOptions } from "fastify"
import fp from "fastify-plugin"

const DummyMessage = Type.String({
  $id: "dummyMessage",
  title: "Dummy Message",
  description: "A dummy message.",
})

const schemasCallback: FastifyPluginCallback<FastifyPluginOptions> = (
  fastify,
  _,
  done,
) => {
  fastify.addSchema(DummyMessage)

  done()
}

export default fp(schemasCallback)

Expected Behavior

No response

Type.Record Generating Incorrect Model in Fastify

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.24.3

Plugin version

4.0.0

Node.js version

v20.11.0

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

Windows 10 Version 1809

Description

Type.Record from the @sinclair/typebox library does not generate a correct model. Model does not match expected structure. Instead it generates a unrelated Generic Model.

{
  "additionalProp1": "string",
  "additionalProp2": "string",
  "additionalProp3": "string"
}

Steps to Reproduce

const TempModel = Type.Record(Type.String(), Type.Number()) 

export const testRoutes: FastifyPluginAsyncTypebox = async (fastify, opts) => 
{
    fastify.post("/data", {
		schema: {
			description: "returns data",
			tags: [TAG_TEST],
			response: {
				200: TempModel,
			}
		}
	}, async (request, reply) => {
        // DO NOTHING

    });
} 

Output

image

Expected Behavior

"String": number

Example:

"test": 123

Support for responses

I could not provide type-checking for the responses of a route. Could you take a look at the following:

import Fastify from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';

const server = Fastify();

server.withTypeProvider<TypeBoxTypeProvider>();

server.get('/', {
  schema: {
    response: {
      200: Type.Object({
        hello: Type.String()
      }, {
        additionalProperties: false
      })
    }
  }
}, async () => {
  return {
    hello: 'world',
    foo: 'bar'
  };
})

server.listen({ port: 3000 })

This compiles safely but shouldn't, as it should catch the mistake.
Just so you know, the schema is correctly applied.

Support for transform types

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Now that TypeBox supports transform types, it would be great if this library supported them as well.

Example

I made a branch that should work here: main...ehaynes99:fastify-type-provider-typebox:transform-types

However, this lib currently allows TypeBox versions down to 0.26, and transform types were only added in 0.30. I could work around it for the actual conversion like here:

// Decode added in TypeBox 0.30
const decoded = ('Decode' in Value) ? Value.Decode(schema, converted) : converted

but there's not a way to fix the types, because StaticDecode would not exist in those older versions. In order to merge this, the compatible version range would have to be updated.

diff --git a/package.json b/package.json
index e6af223..783bda7 100644
--- a/package.json
+++ b/package.json
@@ -18,7 +18,7 @@
     }
   },
   "peerDependencies": {
-    "@sinclair/typebox": ">=0.26 <=0.32"
+    "@sinclair/typebox": ">=0.30 <=0.32"
   },
   "scripts": {
     "build:clean": "rimraf ./dist",

FST_ERR_SCH_VALIDATION_BUILD error when using 'header' validation

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.6.0

Plugin version

2.3.0

Node.js version

16.14.2

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.6

Description

When using Typebox to vaidate headers in a Fastify request handler schema, an error is returned on server startup with code FST_ERR_SCH_VALIDATION_BUILD (stack trace provided in "Steps to Reproduce" section).

There is a workaround for the issue as documented in the " Expected Behavior" section.

Error cause

An error is thrown in fastify library in the following code section: https://github.com/fastify/fastify/blob/21f209f9ad5205d91e7a520ef380f51b8587419f/lib/validation.js#L44.

if condition evaluates to false and the code progresses into the else block. There fastify builds a new plain JS object with lowercase keys, and destroys the original TObject type. This then leads to the aforementioned error when using the TypeBoxValidatorCompiler.

Steps to Reproduce

import Fastify from 'fastify'
import { TypeBoxTypeProvider, TypeBoxValidatorCompiler } from '@fastify/type-provider-typebox'
import { Type } from '@sinclair/typebox'

const server = Fastify()
  .withTypeProvider<TypeBoxTypeProvider>()
  .setValidatorCompiler(TypeBoxValidatorCompiler)

// Validate headers
const schema = {
  headers: Type.Object({
    key: Type.String()
  })
}

server.get('/', { schema }, (req, res) => {
  res.send('OK')
})

server.listen(
  {
    port: 3000,
    host: '0.0.0.0',
  },
  (error) => {
    console.error(error)
  }
)

Error on startup:

FastifyError [Error]: Failed building the validation schema for GET: /, due to error TypeGuard: Invalid type
    at Boot.<anonymous> (/REDACTED/node_modules/fastify/lib/route.js:326:21)
    at Object.onceWrapper (node:events:645:28)
    at Boot.emit (node:events:538:35)
    at /REDACTED/node_modules/avvio/boot.js:160:12
    at /REDACTED/node_modules/avvio/plugin.js:275:7
    at done (/REDACTED/node_modules/avvio/plugin.js:200:5)
    at check (/REDACTED/node_modules/avvio/plugin.js:224:9)
    at node:internal/process/task_queues:141:7
    at AsyncResource.runInAsyncScope (node:async_hooks:201:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:138:8) {
  code: 'FST_ERR_SCH_VALIDATION_BUILD',
  statusCode: 500
}

Expected Behavior

Workaround

# Set prototype of the `TObject` to `null`
// Validate headers
const schema = {
  headers: Object.setPrototypeOf(
    Type.Object({
      key: Type.String()
    }),
    null
  )
}

preHandler types conflict with package `@fastify/auth`

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.0.0-rc.3

Plugin version

No response

Node.js version

16.x

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 20.04

Description

I'm having TypeScript issues in the route preHandler when the package @fastify/auth ^3.0.0 is being used altogether. I'm unsure if this an issue of that package or this, but I've began experiencing issues once .withTypeProvider<TypeBoxTypeProvider>() is called. The error received:

Type 'preHandlerHookHandler<Server, IncomingMessage, ServerResponse, RouteGenericInterface, unknown, FastifySchema, FastifyTypeProviderDefault, ResolveFastifyRequestType<...>, FastifyLoggerInstance>' is not assignable to type 'preHandlerHookHandler<Server, IncomingMessage, ServerResponse, RouteGenericInterface, unknown, FastifySchema, TypeBoxTypeProvider, ResolveFastifyRequestType<...>, FastifyLoggerInstance> | preHandlerHookHandler<...>[] | undefined'.

Steps to Reproduce

Install fastify@4, @fastify/auth@3 and .1.0-beta.1 version of this plugin in a TypeScript environment. Calling the fastify.auth([]) in the route preHandler will give a type error.

Expected Behavior

No response

Can't register a plugin using generics - TypeBoxTypeProvider

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

next

Plugin version

0.1.0-beta.0

Node.js version

16

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

Trying to assign a generic type that uses TypeBoxTypeProvider for plugins.

Steps to Reproduce

type TypeBoxPluginAsync =
FastifyPluginAsync<Record<never, never>, RawServerDefault, TypeBoxTypeProvider>;

const server = fastify({
  ajv: { plugins: [ajvTypeBoxPlugin] },
}).withTypeProvider<TypeBoxTypeProvider>();

const aPlugin: TypeBoxPluginAsync = async (server) => {};

/* Type 'TypeBoxPluginAsync' is not assignable to type 'FastifyPluginCallback<Record<never, never>, Server, FastifyTypeProviderDefault>'. */
server.register(aPlugin); 

Expected Behavior

No error.

Option to use TypeBox TypeCompiler

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

As of TypeBox 0.24.0, this library now offers a specialized TypeCompiler that builds highly optimized validation routines specifically for TypeBox types. To allow users to make use of the compiler, this proposal seeks to expose an TypeBoxValidatorCompiler export that users can optionally set to override the default AJV compiler.

The anticipated usage may look as follows.

import { Type, TypeBoxTypeProvider, TypeBoxValidatorCompiler } from '@fastify/type-provider-typebox'
import Fastify from 'fastify'

const fastify = Fastify().setValidatorCompiler(TypeBoxValidatorCompiler)

fastify.withTypeProvider<TypeBoxTypeProvider>().get('/', {
  schema: {
    querystring: Type.Object({
      x: Type.String(),
      y: Type.Number(),
      z: Type.Boolean()
    })
  }
}, (req) => { ... })

The TypeBoxValidatorCompiler import should viewed as optional an extra from a user (and documentation) standpoint. The compiler itself only builds for a subset of the JSON schema specification. Without configuration, this provider will continue to work with AJV.

Additional Information on the compiler can be found https://github.com/sinclairzx81/typebox#Compiler

Submitting for consideration

Motivation

The following are comparative performance benchmarks measured against TypeBox and AJV for a variety of TypeBox types. Each test iterates several million times and measures the elapsed time to complete benchmark.

The Results

┌──────────────────┬────────────┬───────────────┬───────────────────┬─────────────┐
     (index)       Iterations  Ajv Completed  TypeBox Completed  Performance 
├──────────────────┼────────────┼───────────────┼───────────────────┼─────────────┤
       Any          16000000      '244ms'          '147ms'         '+65%'    
     Boolean        16000000      '257ms'          '150ms'         '+71%'    
     Integer        16000000      '253ms'          '154ms'         '+64%'    
       Null         16000000      '244ms'          '148ms'         '+64%'    
      Number        16000000      '245ms'          '145ms'         '+68%'    
      String        16000000      '246ms'          '152ms'         '+61%'    
     Unknown        16000000      '239ms'          '170ms'         '+40%'    
      RegEx         16000000      '659ms'          '528ms'         '+24%'    
     ObjectA        16000000      '441ms'          '281ms'         '+56%'    
     ObjectB        16000000      '664ms'          '462ms'         '+43%'    
      Tuple         16000000      '295ms'          '189ms'         '+56%'    
      Union         16000000      '299ms'          '209ms'         '+43%'    
    Recursive       16000000     '5221ms'         '1851ms'         '+182%'   
     Vector4        16000000      '291ms'          '168ms'         '+73%'    
     Matrix4        16000000      '589ms'          '377ms'         '+56%'    
 Literal<String>    16000000      '247ms'          '151ms'         '+63%'    
 Literal<Number>    16000000      '240ms'          '148ms'         '+62%'    
 Literal<Boolean>   16000000      '243ms'          '149ms'         '+63%'    
  Array<Number>     16000000      '422ms'          '223ms'         '+89%'    
  Array<String>     16000000      '422ms'          '300ms'         '+40%'    
  Array<Boolean>    16000000      '474ms'          '341ms'         '+39%'    
  Array<ObjectA>    16000000     '3517ms'         '2027ms'         '+73%'    
  Array<ObjectB>    16000000     '6335ms'         '4590ms'         '+38%'    
   Array<Tuple>     16000000     '1404ms'         '1040ms'         '+35%'    
  Array<Vector4>    16000000     '1462ms'          '751ms'         '+94%'    
  Array<Matrix4>    16000000     '6239ms'         '4150ms'         '+50%'    
└──────────────────┴────────────┴───────────────┴───────────────────┴─────────────┘

Example

The following should be the full implementation of the TypeBoxValidatorCompiler. However additional updates may include formatting validation errors to present better as HTTP response messages.

import Fastify from 'fastify'
import { FastifySchemaCompiler, FastifyTypeProvider } from "fastify"
import { TypeCompiler } from '@sinclair/typebox/compiler'
import { Type, Static, TSchema } from '@sinclair/typebox'

export * from '@sinclair/typebox' // review: Ensure Type, Static and other associative types are exported

/** TypeBoxValidatorCompiler */
export const TypeBoxValidatorCompiler: FastifySchemaCompiler<TSchema> = ({ schema }) => {
    const TypeCheck = TypeCompiler.Compile(schema)
    return (data): any => {
        if (TypeCheck.Check(data)) return // ok
        const errors = [...TypeCheck.Errors(data)]
        throw Error(errors.map(({ message, path }) => `${message} for ${path}`).join('. '))
    }
}

/** TypeBoxTypeProvider */
export interface TypeBoxTypeProvider extends FastifyTypeProvider {
    output: this['input'] extends TSchema ? Static<this['input']> : never
}

TypeCompiler could fill defaultValues

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Og. issue: sinclairzx81/typebox#203

Antecedents

Before the last changes to TypeBox and this plugin, using the ajvPlugin was possible to define something like this:

const DEFAULT_PAGINATION = Type.Object({
  limit: Type.Number({ default: 10 }),
  page: Type.Number({ default: 0 }),
});

And it was auto-filled on the req.query object, this was super easy to build /search endpoints where usually the first request you set this fields by default and if you need to paginate then, you pass the params.

Actual

Now, this doesn't work anymore and it crashes even if you pass a number to the querystring:

errors: [
    {
      schema: { default: 0, type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
      path: '/page',
      value: undefined,
      message: 'Expected number'
    },
    {
      schema: { default: 10, type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
      path: '/limit',
      value: undefined,
      message: 'Expected number'
    }
  ]

Expected

Imho, we should have a way to enable this kind of serialization, (I understand that probably doesn't match the json-schema bible, but it makes much much easier to use and work with the api, removing a lot of duplicated code)

Motivation

Making it easier to work with this plugin and work more-like other validators/compilers.

Example

No response

Add JSDoc Support

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Unfortunately, Typescript doesn't support inline generics with JSDoc, yet. microsoft/TypeScript#27387
But AFAIK, there should be no difference between JSDoc and Typescript on this matter.
I tried to make it work without the need to override the type again and again but failed.
I'm not a Typescript expert, so I would appreciate it if someone could take a look.

Motivation

Use Typebox provider in JS + JSDoc projects (typescript only as a type checker without compiling the code)

Example

No response

Can't run project with fastify-type-provider-typebox

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

next

Plugin version

main

Node.js version

16.12

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

C:\project>npm run start
> start
> node index.js

node:internal/modules/cjs/loader:361
      throw err;
      ^
Error: Cannot find module 'C:\project\node_modules\@fastify\type-provider-typebox\dist\index.js'. Please verify that the package.json has a valid "main" entry
    at tryPackage (node:internal/modules/cjs/loader:353:19)
    at Function.Module._findPath (node:internal/modules/cjs/loader:566:18)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:\project\index.js:7:33)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32) {
  code: 'MODULE_NOT_FOUND',
  path: 'C:\\project\\node_modules\\@fastify\\type-provider-typebox\\package.json',
  requestPath: '@fastify/type-provider-typebox'
}

Steps to Reproduce

Build typescript and run project (index.js).

index.ts:

import Fastify from 'fastify'
import { ajvTypeBoxPlugin, TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import { Type } from '@sinclair/typebox'

const fastify = Fastify({
  ajv: {
    plugins: [ajvTypeBoxPlugin]
  }
}).withTypeProvider<TypeBoxTypeProvider>()

fastify.get('/', {
    schema: {
      body: Type.Object({
        x: Type.String(),
        y: Type.Number(),
        z: Type.Boolean()
      })
    }
  }, (req) => {
    // The `x`, `y`, `z` types are automatically inferred
    const { x, y, z } = req.body
  })

  fastify.listen(3000, (err, address) => {
    if (err) throw err
    // Server is now listening on ${address}
  })

Repro repo:
https://github.com/rubenferreira97/FastifyTypeBoxBug

Expected Behavior

Run without errors.

Doesn't support auto-coercion for response bodies

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.26.1

Plugin version

4.0.0

Node.js version

v20.11.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

14.3 (23D56)

Description

I filed an issue and submitted a PR over on fast-json-stringify fastify/fast-json-stringify#683 but this affects the stack at different layers, apparently. Basic example:

fastify.get('/y', {
  schema: {
    response: {
      200: Type.Object({
        x: Type.String({ format: 'date-time' }),
      })
    }
  }
}, () => {
  return {
    x: new Date()
  }
})

This produces this TypeScript error:

server/fastify.ts:77:3 - error TS2345: Argument of type '() => { x: Date; }' is not assignable to parameter of type 'RouteHandlerMethod<Server<typeof IncomingMessage, typeof ServerResponse>, IncomingMessage, ServerResponse<IncomingMessage>, ... 4 more ..., FastifyBaseLogger>'.
  Type '{ x: Date; }' is not assignable to type 'void | { x: string; } | Promise<void | { x: string; }>'.
    Type '{ x: Date; }' is not assignable to type '{ x: string; }'.
      Types of property 'x' are incompatible.
        Type 'Date' is not assignable to type 'string'.

77   () => {
     ~~~~~~~

But the code works as you'd expect - fast-json-stringify is able to stringify that Date object into an ISO Date string. fast-json-stringify has an explicit list of these conversions and they work, but they aren't supported at this level.

I think the core of this issue is that this module is using Static from TypeBox to derive types. But that is strict: the static type of a Type.String is just a string:

https://github.com/sinclairzx81/typebox/blob/fd1056b367479c7a9925143641d272b4a238ffad/src/type/string/string.ts#L77-L81

There's a StaticEncode type in TypeBox, but that's for custom types, not for defaults.

Anyway, this is a rough issue if you're using a database setup that produces JavaScript Date objects for date columns and you've been relying on their default stringification. And it works, but the types don't work and there's no easy workaround.

I'm open to suggestions from the maintainers about how this could be resolved. Off the top of my head I'm guessing:

  • Pull the type coercion tricks from fast-json-stringify into a type that this can import, or can live in this module.
  • Try to submit a PR upstream to Typebox (but this doesn't seem like it'd be accepted because the output coercion isn't a Typebox thing)
  • Some secret third thing?

Steps to Reproduce

Try using default stringification with a body, like:

fastify.get('/y', {
  schema: {
    response: {
      200: Type.Object({
        x: Type.Number({ format: 'date-time' }),
      })
    }
  }
}, () => {
  return {
    x: new Date()
  }
})

Expected Behavior

The types for this module should reflect what's possible with the code.

Validator crashes fastify application upon invalid / undefined field value

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.3.0

Plugin version

No response

Node.js version

16.15.1

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

When the fastify validator calls the validator function (https://github.com/fastify/fastify/blob/66fc397212531c2565a9cb86a2c0f4a2f06a8c77/lib/validation.js#L79), it checks if a return is type or has an error on it.

The TypeBox provider actually throws an excetion (

throw new TypeBoxValidationError([...typeCheck.Errors(value)])
), which causes fastify to crash the entire application since there is no try-catch on this request phase.

image

Steps to Reproduce

  • Create a simple application using the TypeBox provider
  • Register a route with a given schema (I have tested with a body param)
  • Try to make a request to the route with a missing field
fastify.route({
    method: "POST",
    url: "/user/sign-up",
    schema: {
        body: Type.Object({
            email: Type.String()
        })
    },
    handler() { }
})

Expected Behavior

No response

Is there way to create wrapper function for route handler inferring schema type?

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

This is more about TS question... sorry about asking it here.

I have a simple Fastify route. my fastify is using fastify.withTypeProvider<TypeBoxTypeProvider>();

    fastify.post(
      'v1/article',
      {
        schema: {...},
      },
      async (request, reply) => {
        // everything is good and `request` has inferred schema type.
        reply.send("ok");
      }
    );

I want to create a wrapper for the route handler

    fastify.post(
      'v1/article',
      {
        schema: {...},
      },
      myWrapper(async (request, reply) => {
        // type is lost and reply becomes unknown!
       // and I can't infer schema type here
        reply.send("ok");
      })
    );

This looks simple thing to do but I failed to pass inline function's type to my wrapper's parameter.

I've tried something like below

const myWrapper = <RQ, RP>(handler: (req: RQ, rep: RP) => Promise<void>) => {
  return async (req: RQ, rep: RP) => {
    await handler(req, rep);
  };
};

or

const myWrapper = <T, A extends unknown[]>(handler: (...args: A) => T) => {
  return handler;
};

But this doesn't work and not passing inline function's type to my wrapper's parameter function... I know what's wrong here but is there any way to solve my issue?

(I can't use types provided from Fastify because I need type inferring from the schema)

Thanks

Release 3.1.0 broke type inference on fastify route handler request parameter

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.15.0

Plugin version

3.1.0

Node.js version

16.19.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

Monterey 12.6.5

Description

Hi,

Just updated plugin to version 3.1.0 recently and it looks like I lost types inference on the fastify routes handler request object. I rollbacked to 3.0.0 which is working fine. The following screenshot is showing that I no longer get types inference on the params object of the fastify request despite schema definition being provided and Typebox type provider being used.

image

Thank you for your help ;)

Steps to Reproduce

import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';
import fastify from 'fastify';

fastify()
  .withTypeProvider<TypeBoxTypeProvider>()
  .get('/', {
    schema: {
      params: Type.Object({
        foo: Type.String()
      })
    },
    handler(req, rep) {
      console.log(req.params.foo);
      rep.send();
    }
  });

Expected Behavior

  • In the previous example, req.params.foo should be typed as a string.
  • Using strict flag with typescript, I should not get the following error:
'req.params' is of type 'unknown'.ts(18046)

TypeBox no longer requires explicit configuration of kind and modifier keywords

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hi. Just a heads up. I've recently published a new version of TypeBox that should mitigate the need to configure AJV for the kind and modifier keywords. As of @sinclair/[email protected], the kind and modifier keywords have been replaced as symbol property keys. This seems to sidestep the AJV strict checks allowing TypeBox schemas to be used without any explicit configuration.

Before

const StringKind = Symbol('StringKind')

const T = {
   kind: StringKind
   type: 'string'
}

After

const Kind = Symbol('TypeBox.Kind')

const T = {
   [Kind]: 'String' // AJV should ignore properties defined as symbols
   type: 'string'
}

The TypeBox type provider will continue to function with this existing kind and modifier configuration, however it may be good to remove the ajvTypeBoxPlugin export and update the documentation accordingly.

Current

import Fastify from 'fastify'
import { ajvTypeBoxPlugin, TypeBoxTypeProvider } from '@fastify/type-provider-typebox'

const fastify = Fastify({
  ajv: {
    plugins: [ajvTypeBoxPlugin]
  }
}).withTypeProvider<TypeBoxTypeProvider>()

Update

import Fastify from 'fastify'

import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'

const fastify = Fastify().withTypeProvider<TypeBoxTypeProvider>()

Add Support Typebox 0.25.x

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Support Fastify 1.25.x so that we can use the latest typebox types.

Motivation

Fastify 1.25 adds some new types that we would like to use

Example

No response

Support typebox 0.27.8

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Support Typebox 0.27.8, currently we use "@sinclair/typebox": "^0.26.4" in package.json.

Motivation

The versions in the meantime have some nifty features :)

Example

This example from Typebox docs does not work with the current version 0.26.4:

type PointOptions = { }                              // The Type Options

type PointType = { x: number, y: number }            // The Static<T> Type

const Point = TypeSystem.Type<PointType, PointOptions>('Point', (options, value) => {
  return (
    typeof value === 'object' && value !== null &&
    typeof value.x === 'number' && 
    typeof value.y === 'number'
  )
})

const T = Point()

type T = Static<typeof T>                            // <-- throws type error

const R = Value.Check(T, { x: 1, y: 2 })              // const R = true

incorrect (and potentially broken) dependency resolution error when installing latest via NPM

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.19.1

Plugin version

3.2.0

Node.js version

18.12.1

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

windows 10 build 19044.3086

Description

as per installation instructions (in this page as well as fasitfy docs when you install the package via

npm i @sinclair/typebox @fastify/type-provider-typebox

it fails with below error.

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: @fastify/[email protected]
npm ERR! Found: @sinclair/[email protected]
npm ERR! node_modules/@sinclair/typebox
npm ERR! @sinclair/typebox@"^0.29.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @sinclair/typebox@"^0.28.0" from @fastify/[email protected]
npm ERR! node_modules/@fastify/type-provider-typebox
npm ERR! @fastify/type-provider-typebox@"^3.2.0" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @sinclair/[email protected]
npm ERR! node_modules/@sinclair/typebox
npm ERR! peer @sinclair/typebox@"^0.28.0" from @fastify/[email protected]
npm ERR! node_modules/@fastify/type-provider-typebox
npm ERR! @fastify/type-provider-typebox@"^3.2.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Steps to Reproduce

just follow the documentation and install

npm i @sinclair/typebox @fastify/type-provider-typebox

Expected Behavior

It should not throw an error and properly setup

Adding multiple items to the security array of the JSON Schema breaks all the types

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.5.3

Plugin version

2.3.0

Node.js version

18.7.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.5.2

Description

We have a problem that our types are not automatically inferred when we add multiple items to the security property of the JSON schema that you can define on the route.

You can see this in the example below:

Steps to Reproduce

import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';
import Fastify from 'fastify';

export const fastify = Fastify().withTypeProvider<TypeBoxTypeProvider>();

fastify.get('/', {
  schema: {
    body: Type.Object({
      x: Type.String(),
      y: Type.Number(),
      z: Type.Boolean(),
    }),
    // Adding multiple items here breaks the automatically type inferring. 
    security: [{ OAuth2: ['x:readOnly'] }, { OpenIDConnect: [] }],
  },
}, (req) => {
  // The `x`, `y`, `z` types are not inferred anymore because there are multiple items in the array
  const { x, y, z } = req.body;
});

Expected Behavior

We'd like that our types are inferred when adding multiple items to the security array.

Fastify fails to work with FormatRegistry from TypeBox

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.26.2

Plugin version

No response

Node.js version

21.7.1

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

22.04.4 TLS x86_64

Description

TypeBox provides FormatRegstry which allows extending its string validation to custom formats.

When attempting to use a custom FormatRegistry registered string format in the schema of a Fastify endpoint, Fastify fails to run.

I'm not sure if this is a fastify or fastify-type-provider-typebox issue, but I suspect the issue lies with the type provider.

Steps to Reproduce

I've created a reproduction of this as a Git repo here.

The README contains the steps to reproduce the issue.

Expected Behavior

Fastify shouldn't throw a runtime error of FastifyError [Error]: Failed building the validation schema for POST: /asdf, due to error unknown format "foo" ignored in schema at path "#/properties/bar"

string auto convert to number

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.2.0

Plugin version

No response

Node.js version

18.0

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

win10

Description

use fastify with TypeBoxTypeProvider,validate will auto cast sting to number,and auto cast sting to string[]

for example code blow:

Steps to Reproduce

//server.ts
const server = fastify().withTypeProvider<TypeBoxTypeProvider>()
fastify.post<
            { Body: User[] }
        >('/marks', { schema: { body: properties} }, async (request, reply) => {
            try {
                reply.code(200).send()
            } catch (err) {
                reply.code(400).send(err)
            }
        }),

//validate.ts
export const properties = Type.Object({
   timestamp: Type.Readonly(Type.Integer()),
   users:Type.Optional(Type.Array(Type.String()))
})



//testData1:
{
   timestamp:1683687611279,
   users:["tom","jerry"]
}
expect:OK
result:OK

//testData2:
{
   timestamp:"1683687611279",
   users:"tom"
}
expect:False
result:OK

Expected Behavior

No response

`Type.Void` / `Type.Undefined` throws `FST_ERR_SCH_SERIALIZATION_BUILD` since typebox 0.30.0

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.23.2

Plugin version

3.5.0

Node.js version

18.15.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

13.5.2

Description

https://github.com/sinclairzx81/typebox/blob/master/changelog/0.30.0.md#Extended-Type-Representation-Change might have produced this regression.

Below example will produce an error since 0.30.0 (0.29.6 was fine, i'm using 0.31.16) :
FastifyError [Error]: Failed building the serialization schema for GET: /test, due to error schema is invalid: data/type must be equal to one of the allowed values

Steps to Reproduce

import { type TypeBoxTypeProvider, Type } from '@fastify/type-provider-typebox'
import fastify from 'fastify'

async function main () {
  const webServer = fastify().withTypeProvider<TypeBoxTypeProvider>()

  webServer.route({
    method: 'GET',
    url: '/test',
    handler: () => { },
    schema: {
      response: {
        200: Type.Void()
      }
    }
  })

  //
  await webServer.ready()
}

//
main()
  .catch((error) => {
    console.error(error)
    process.exit(1)
  })

Expected Behavior

void should still be considered a valid validation value by ajv, as it describes an absence of returned value, which is not very user-friendly API-wise, but still useful for mocking.

Export TypeBox `Type.*` object on provider

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Hi. I'm wondering if it might be possible to export the TypeBox Type.* namespace on this provider. This to simplify usage and avoid an additional import of @sinclair/typebox.

Motivation

I think in the context of Fastify, having the Type.* namespace be exported on the @fastify/type-provider-typebox package would be quite nice for the end user as the provider would export all the necessary infrastructure without requiring an additional import of @sinclair/typebox.

Example

$ npm install fastify @fastify/type-provider-typebox --save
import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import Fastify from 'fastify'

Fastify().withTypeProvider<TypeBoxTypeProvider>().get('/', {
  schema: {
    querystring: Type.Object({
      offset: Type.Number(),
      limit: Type.Number()
    })
  }
}, (req, res) => {
  const { offset, limit } = req.query
})

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.