fastify / fastify/help

Schema generation with decorator metadata

Open
#396 4 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

## 💬 Question here

In the Fastify docs it's mentioned that the schema definition for response serialization should be treated as application code and that it is not safe to use user-provided schemas.
But in my application I want to generate the schemas from the metadata provided by the user via TypeScript decorators.

```js
import "reflect-metadata";

const prop = (target: Object, propertyKey: string): void => {
const propertyType = Reflect.getMetadata( "design:type", target, propertyKey ).name;

const props = Reflect.getMetadata( "PROPERTIES", target.constructor ) ?? [];

props.push( { propertyKey, propertyType } );

Reflect.defineMetadata( "PROPERTIES", props, target.constructor );
};

class User {
@prop
id: number;

@prop
name: string;
}

const generateSchema = (ctor: { new(...arg: any[]): T }): Record => {
const schema: Record = {
type: 'object',
properties: {}
};

const properties = Reflect.getMetadata( "PROPERTIES", ctor );

properties.forEach((prop: any) => {
schema.properties[prop.propertyKey] = {
type: prop.propertyType.toLowerCase()
}
})

return schema;
};

/*
{
type: "object",
properties: {
id: {
type: "number"
},
name: {
type: "string"
}
}
}
*/
const schema = generateSchema( User )

````
It is safe to generate schemas this way?

## Your Environment

- *node version*: 14
- *fastify version*: >=3.14.0
- *os*: Mac

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.