Serialization
Fastify’s performance is enhanced by solving the serialization problem when using JSON.stringify
and JSON.parse
.
Deep dive into this topic by watching Matteo Collina’s talk:
These concepts are a Fastify feature, in which Kita takes full advantage of.
Kita runs at build time, inferring all I/O types for each route and generating route schemas. This enables Fastify to use a super fast serializer and super fast validator.
Parsing the request
Kita uses Ts Json Schema Generator under the hood to transform TypeScript AST TypeNodes into a JSON schema.
This is what powers the complex transformation of code types into JSON schemas. Take a look at the following example:
export interface CreateUser {
/**
* The name of the user
*
* @minLength 3
* @maxLength 20
*/
name: string;
/**
* The email of the user
*
* @format email
*/
email: string;
/**
* The age of the user
*
* @minimum 0
* @maximum 150
*/
age: number;
}
2
3
4
5
6
7
8
{
"CreateUserRequest": {
"additionalProperties": false,
"properties": {
"age": {
"description": "The age of the user",
"maximum": 150,
"minimum": 0,
"type": "number"
},
"email": {
"description": "The email of the user",
"format": "email",
"type": "string"
},
"name": {
"description": "The name of the user",
"maxLength": 20,
"minLength": 3,
"type": "string"
}
},
"required": ["name", "email", "age"],
"type": "object"
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
You can use the above interface inside a route handler:
import type { Body } from '@kitajs/runtime';
interface CreateUser {
name: string;
email: string;
age: number;
}
export function post(data: Body<CreateUser>) {
return true;
}
{
"paths": {
"/": {
"post": {
"operationId": "postIndex",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CreateUserRequest"
}
}
}
},
"responses": {
"2XX": {
"description": "Default Response",
"content": {
"application/json": {
"schema": {
"type": "boolean"
}
}
}
}
}
}
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
The above schema is handled by Fastify & Ajv, ensuring that the request body matches the expected types as well as the constraints defined in the interface, such as @minLength
, @maxLength
, @format
, @minimum
, and @maximum
.
Ajv, the library used underneath, is trusted by millions of developers and multiple big companies for its speed and reliability.