Skip to main content
Version: v2

Transformers

Transformers allow modifying a primitive (string, number etc.) or any attribute value during the transformation step:

const PREFIX = 'POKEMON#'

const prefix = {
// Updates the value during parsing
encode: (input: string) => [PREFIX, input].join(''),
// Updates the value back during formatting
decode: (saved: string) => saved.slice(PREFIX.length)
}

// Saves the prefixed value
const pokemonIdSchema = string().transform(prefix)
const pokemonIdSchema = string({ transform: prefix })

Some transformers are available off-the-shelf:

  • prefix: Prefixes a string value
  • suffix: Suffixes a string value
  • jsonStringify: Applies JSON.stringify to any value
  • pipe: Merge multiple transformers into a single transformer

When applicable, we strongly recommend using those instead of custom transformers as they are type-safe (using hotscript), serializable and chainable using the pipe(...) method:

const transformer = jsonStringify()
.pipe(prefix('PREFIX'))
.pipe(suffix('SUFFIX'))

transformer.encode({ foo: 'bar' }) // => 'PREFIX#{"foo":"bar"}#SUFFIX'
note

If you need a new transformer, feel free to open an issue or submit a PR πŸ€—