Schema enhancements

Im trying to build some generic schema factory methods that can take in domain schemas and create json:api compatible effect schemas from them.
This is what im trying to achieve:

const Resource = User.pipe(
    JAS.resource({
      type: 'user',
      idKey: 'userId',
    }),
    // ... more here
  )

  const decode = Resource.pipe(S.decode)
  const encode = Resource.pipe(S.encode)

  const result = encode({
    userId: '1',
    age: 25,
    name: 'John',
  })

  const expectedType = E.right({
    id: '1',
    type: 'user',
    attributes: {
      name: 'John',
      age: 25
    },
  })


What I have right now is this:
export const resource =
  <B extends Record<string, any>, T extends S.Struct<B>, U extends keyof T, K extends string>({ idKey, type }: { idKey: U; type: K }) =>
  (PlainObject: T) => {
    return S.transform(
      S.Struct({
        id: S.String,
        type: S.Literal(type),
        attributes: S.typeSchema(PlainObject),
      }),
      {
        strict: true,
        encode: (value) => {
          const t = {
            id: '' + value[idKey as keyof typeof value],
            type: type,
            attributes: omit(value, idKey as keyof typeof value) as Exclude<typeof value, U>,
          };
          return t
        },
        decode: (value) => {
          return {
            ...value.attributes,
            [idKey]: value.id as string,
          };
        },
      },
    )
  };


But the issue is that this depends on the the schema being passed in to be of type "Struct", while I may want to pass in a transformed Struct for example. Is there a way to just specifiy a schema shape.
Was this page helpful?