Southclaws / supervillain

Converts Go structs to Zod schemas
MIT License
76 stars 6 forks source link

Fix ordering #6

Closed anthonyLock closed 1 year ago

anthonyLock commented 1 year ago

There was a issue where if you had a struct being called in a sub struct and in the top struct level, and that being after all the others it was causing a typescript issue.

I have extended the testEverything to include the edge case. Without my fix the output would be

assert.Equal(t,
        `export const PostWithMetaDataSchema = z.object({
  Title: z.string(),
  Post: PostSchema,
})
export type PostWithMetaData = z.infer<typeof PostWithMetaDataSchema>

export const PostSchema = z.object({
  Title: z.string(),
})
export type Post = z.infer<typeof PostSchema>

export const UserSchema = z.object({
  Name: z.string(),
  Nickname: z.string().nullable(),
  Age: z.number(),
  Height: z.number(),
  OldPostWithMetaData: PostWithMetaDataSchema,
  Tags: z.string().array().nullable(),
  TagsOptional: z.string().array().optional(),
  TagsOptionalNullable: z.string().array().optional().nullable(),
  Favourites: z.object({
    Name: z.string(),
  }).array().nullable(),
  Posts: PostSchema.array().nullable(),
  Post: PostSchema,
  PostOptional: PostSchema.optional(),
  PostOptionalNullable: PostSchema.optional().nullable(),
  Metadata: z.record(z.string(), z.string()).nullable(),
  MetadataOptional: z.record(z.string(), z.string()).optional(),
  MetadataOptionalNullable: z.record(z.string(), z.string()).optional().nullable(),
  ExtendedProps: z.any(),
  ExtendedPropsOptional: z.any(),
  ExtendedPropsNullable: z.any(),
  ExtendedPropsOptionalNullable: z.any(),
  ExtendedPropsVeryIndirect: z.any(),
  NewPostWithMetaData: PostWithMetaDataSchema,
  VeryNewPost: PostSchema,
})
export type User = z.infer<typeof UserSchema>

`, StructToZodSchema(User{}))
}

This would cause a typescript error Block-scoped variable 'Post' used before its declaration. typescript error as PostWithMetaDataSchema is being used before the declaration of the object.