Effect CommunityEC
Effect Community2y ago
10 replies
hdoro

Transforming Form Schemas to DB-friendly Objects

I'm trying to get a grasp of how to compose schemas in larger transformations. I have a large form schema that has perhaps a total of ~8 subschemas, which I'm transforming to a DB-friendly object to store on user submission.

To start, I've created a tiny example that works well, but I was wondering if I should really be using subschemas' S.encode/decodeSync in my transformer's encode/decode function.

Is there a better way to do it than the example below?

import * as S from '@effect/schema/Schema'

declare function generateId(): string

const FORM_VALUE = {
  names: [
    {
      id: 'throwaway-uid',
      value: 'name',
    },
  ],
}

const DB_INSERT_VALUE = {
  names: ['name'],
}

const NameInForm = S.Struct({ value: S.String, id: S.String })

const nameTransformer = S.transform(NameInForm, S.String, {
  decode: (nameInForm) => nameInForm.value,
  encode: (name) => ({ value: name, id: generateId() }),
})

const FormSchema = S.Struct({
  names: S.Array(NameInForm),
})

const InsertSchema = S.Struct({
  names: S.Array(S.String),
})

const transformer = S.transform(FormSchema, InsertSchema, {
  decode: (formValue) => ({
    names: formValue.names.map((name) => S.decodeSync(nameTransformer)(name)),
  }),
  encode: (insertValue) => ({
    names: insertValue.names.map((name) => S.encodeSync(nameTransformer)(name)),
  }),
})
Was this page helpful?