fastify / fastify/help

Using ajv plugins with Typebox

Open
#794 0 comments 0 reactions 0 assignees View on GitHub
help wanted
Dominant language
No language data
Stars
68
Forks
8
Avg merge
11h 2m
Merged PRs (30d)
2

Description

## 💬 Using ajv-keywords plugin with Typebox - got confused 🙈
AKA case-insensitive validation :)

I'm trying to validate the request body, where one of the params is a simple union `'a' | 'b'`. But the client sometimes sends `'A'` or `'B'`, which is also fine by me. My Typebox object is
```js
const unionSchema = Type.Union([
Type.Literal('a'),
Type.Literal('b')
]);
```

In order to achieve the case-insensitivity, I tried to use the 'transform' option of the [ajv-keywords](https://github.com/ajv-validator/ajv-keywords/tree/v3.4.1#transform) plugin.
Well, great - I even found an example on how to add the plugin in the [docs](https://www.fastify.io/docs/latest/Reference/Server/#ajv)! But unfortunately, the [plugin usage example](https://www.fastify.io/docs/latest/Reference/Validation-and-Serialization/#ajv-plugins) was not relevant neither to `ajv-keywords` nor to Typebox, and the [Typebox section of docs](https://www.fastify.io/docs/latest/Reference/Type-Providers/#typebox) simply sends to Typebox docs for ajv plugins usage, and there's no much info on it.

I added these to app init
```js
import ajvKeywords from "ajv-keywords";

const app = fastify({
ajv: {
plugins: [
[ajvKeywords, 'transform']
]
}
});
```
So I tried:
```js
const providerSchema = Type.Union([
Type.Literal('salesforce', {transform: 'toLowerCase'}),
Type.Literal('servicenow', {transform: 'toLowerCase'})
]);
```
and
```js
const providerSchema = Type.Union([
Type.Literal('salesforce'),
Type.Literal('servicenow')
], {transform: 'toLowerCase'});
```
But in both cases the app won't even start, without giving any error message - just states "✨ Done in 3.36s." and that's all (btw, it's a strange behavior I observe in many cases - is there a way to see the actual errors?)

So the question is - how do I use this wonderful `transform` `ajv-keyword` in the Typebox schema declaration? Just gone round all the docs I could find, and couldn't find the answer 😔

## Your Environment

- *node version*: 16.15.0
- *fastify version*: 4.9.2
- *os*: Mac

P.S.: I'm new to Fastify, and I like it SO much meanwhile :) a very impressive combination of simplicity and power :)))

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.