xddq / schema2typebox

Creating TypeBox code from JSON schemas
MIT License
66 stars 15 forks source link

We should export the type and TypeBox under different names? #34

Closed jamesrusso closed 10 months ago

jamesrusso commented 11 months ago

Library version: 1.6.2

JSON schema version: draft-07

I am willing to contribute to fix the issue 💚

The current behavior

The exported code includes the same name for both the type and the object.

export type CollectorSchema = Static<typeof CollectorSchema>;
export const CollectorSchema = Type.Object({
  name: Type.String({ title: "Name" }),
  taskDefinition: Type.String({ title: "Taskdefinition" }),
});

This makes using validation not possible since I cannot export both from a file.

interface ValidationFactoryReturn<T> {
  schema: TObject;
  verify: (data: T) => T;
}

export const validationFactory = <T>(schema: TObject): ValidationFactoryReturn<T> => {
  const ajv = addFormats(new Ajv({}), [
    'date-time',
    'time',
    'date',
    'email',
    'hostname',
    'ipv4',
    'ipv6',
    'uri',
    'uri-reference',
    'uuid',
    'uri-template',
    'json-pointer',
    'relative-json-pointer',
    'regex',
  ]);

  const C = ajv.compile(schema);
  const verify = (data: T): T => {
    const isValid = C(data);
    if (isValid) {
      return data;
    }
    throw new Error(JSON.stringify(C.errors));
  };

  return { schema, verify };
};

const validateCollector = validationFactory<CollectorSchema>(Collector);

The expected behavior

I would think it would be better to be able to name these differently, one representing the type and one representing the object.

export type CollectorSchema = Static<
  typeof Collector
>;
export const Collector = Type.Object({ ... })

Why does it happen? What/How to fix the issue?

The code currently just uppercases the first character and uses that as the type name.

Content of minimal json schema file which causes the problem

I will provide a more concrete example to this ticket

xddq commented 11 months ago

This makes using validation not possible since I cannot export both from a file.

Works without issues for me, can you provide a reproduction repo?

xddq commented 10 months ago

closing this, if you still have problems please open an issue with a reproduction.