Apollo314 / openapi-to-zod

MIT License
3 stars 2 forks source link

Type annotations can only be used in TypeScript files #2

Closed robogeek closed 11 months ago

robogeek commented 11 months ago

I'm compiling the generated code using TypeScript and get this error:

Type annotations can only be used in TypeScript files

The relevant generated code is:

         const errors = schemas.reduce(
            (errors: z.ZodError[], schema) =>
              ((result) =>
                "error" in result ? [...errors, result.error] : errors)(
                schema.safeParse(x)
              ),
            []
          );

The error indicator points at the z.zodError[], and indeed (errors: type) => { function code } is a type annotation according to Type Script.

This appears at the end of nearly 1600 lines of generated code. The field in the schema where the generated code comes from is this:

        object:
          type: object
          description: the object that is the subject of the notification.
          example: {}
          oneOf:
            - $ref: '#/components/schemas/program'
            - $ref: '#/components/schemas/report'
            - $ref: '#/components/schemas/event'
            - $ref: '#/components/schemas/subscription'
            - $ref: '#/components/schemas/ven'
            - $ref: '#/components/schemas/resource'
          discriminator:
            propertyName: objectType

The structure of the generated code is:

object: z
    .record(z.any())
   .and(
        z.any().superRefine((x, ctx) => {
          const schemas = [
              // 6 z.object instances  - that probably correspond to the oneOf 
          ];
const errors = schemas.reduce(
            (errors: z.ZodError[], schema) =>
              ((result) =>
                "error" in result ? [...errors, result.error] : errors)(
                schema.safeParse(x)
              ),
            []
          );
          if (schemas.length - errors.length !== 1) {
            ctx.addIssue({
              path: ctx.path,
              code: "invalid_union",
              unionErrors: errors,
              message: "Invalid input: Should pass single schema",
            });
          }
        })
      )
      .describe("the object that is the subject of the notification."),
Apollo314 commented 11 months ago

Hi, I wasn't aware that the generated code could have type annotations. Thank you. Anyway, I added a flag -x that you can use to generate .ts files instead of .js files. It should get rid of that error for you.

npx openapi-to-zod -i yourinput -o /output/path -x ts

should generate .ts files now.

you should delete .js files previously generated.

robogeek commented 11 months ago

Thank you, this fixed the issue.