Skip to main content

Formatter

Given a saved item, validates that it respects the schema and formats it:

import { Formatter } from 'dynamodb-toolbox/schema/actions/format'

const formattedPikachu = pokemonSchema
.build(Formatter)
.format(savedPikachu)

In DynamoDB-Toolbox, formatting is done in 2 steps:

Note that:

  • Additional and hidden fields are omitted, but inputs are not mutated
  • The formatting throws an error if the saved item is invalid
  • Transformations (i.e. savedAs and transforms) are applied (backward) by default

Methods

format(...)

(savedValue: unknown, options?: FormatValueOptions) => FormattedValue<SCHEMA>

Formats a saved item:

const formattedValue = pokemonSchema.build(Formatter).format(savedValue)

You can provide formatting options as a second argument. Available options:

OptionTypeDefaultDescription
transformbooleantrueWhether to transform back the input (with savedAs and transform) prior to formatting or not.
formatbooleantrueWhether to format the input (hide hidden attributes) after transformation.

No effect if transform is set to false.
partialbooleanfalseAllow every attribute (flat or deep) to be optional while formatting.
attributesPath<Schema>[]-To specify a list of attributes to format (other attributes are omitted).

See the PathParser action for more details on how to write attribute paths.
Examples
const transformed = {
pokemonId: 'pikachu1',
name: 'Pikachu'
}

// 🙌 Typed as `DeepPartial<FormattedPokemon>`
const formatted = pokemonSchema
.build(Formatter)
.format(transformed, { partial: true })

You can use the FormattedValue type to explicitly type an object as a formatting output object:

import type { FormattedValue } from 'dynamodb-toolbox/format'

const formattedValue: FormattedValue<
typeof pokemonSchema,
// 👇 Optional options
{ partial: false; attributes: 'name' | 'level' }
// ❌ Throws a type error
> = { invalid: 'output' }

start(...)

(input: unknown, options?: FormatValueOptions) => Generator<FormattingResults<SCHEMA>>

Similar to .format, but returns the underlying Generator to inspect the intermediate results of the formatting steps:

Examples
const formattingGenerator = pokemonSchema
.build(Formatter)
.start(pokemon)

const transformedPokemon = formattingGenerator.next().value
const formattedPokemon = formattingGenerator.next().value

validate(...)

(input: unknown) => boolean

Runs only the transform step of the formatting workflow on the provided input. Returns true if the input is valid, catches any parsing error and returns false otherwise:

const isValid = pokemonSchema
.build(Formatter)
.validate(input)

Note that .validate(...) acts as a type guard:

if (pokemonSchema.build(Formatter).validate(input)) {
// 🙌 Typed as `TransformedPokemon`!
const { level, name } = input
...
}