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 astring
valuesuffix
: Suffixes astring
valuejsonStringify
: AppliesJSON.stringify
to any valuepipe
: 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 π€