DZakh / rescript-schema

🧬 The fastest parser in the entire JavaScript ecosystem with a focus on small bundle size and top-notch DX
MIT License
162 stars 7 forks source link

How to deal with nested data structure? #53

Closed pd4d10 closed 1 year ago

pd4d10 commented 1 year ago

For example:

type rec t = File({content: string}) | Directory({files: array<t>})
DZakh commented 1 year ago

You can use S.recursive for this:

type rec t = File({content: string}) | Directory({files: array<t>})

let struct = S.recursive(struct =>
  S.union([
    S.object(o => {
      o->S.field("tag", S.literal(String("file")))->ignore
      File({content: o->S.field("content", S.string())})
    }),
    S.object(o => {
      o->S.field("tag", S.literal(String("directory")))->ignore
      Directory({files: o->S.field("files", S.array(struct))})
    }),
  ])
)