fastify / help

Need help with Fastify? File an Issue here.
https://www.fastify.io/
65 stars 8 forks source link

Schema generation with decorator metadata #396

Open matthyk opened 3 years ago

matthyk commented 3 years ago

💬 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.

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 = <T>(ctor: { new(...arg: any[]): T }): Record<string, any> => {
  const schema: Record<string, any> = {
    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

L2jLiga commented 3 years ago

Hello,

I think answer is yes, it's safe if you know that generated schema will be valid JSON schema

mcollina commented 3 years ago

It's safe as long as you do no fetch it from a database.

matthyk commented 3 years ago

Would a plugin that provides this functionality be useful?

L2jLiga commented 3 years ago

I think plugin not really needed, however if you have good ideas you can implement general purpose library, for example can take a look on https://github.com/eddow/ts-json-schema-decorator