Data
Overview
Associating arbitrary data with your basket can be necessary in many cases. For instance, you might want to store shipping information or other important information during the checkout process.
To accommodate this, declo provides a .data(...)
configuration option which allows you define an outline of the data structure you want to store.
Defining a schema
To ensure the integrity of the data, you are required to define the schema of the data you want to store.
The schema
field supports a variety of popular third-party validation libraries, or you can provide your own validation function.
Supported libraries include:
But any library compatible with the following signature can be used:
type Parser =
| { parse: (input: unknown) => T }
| { create: (input: unknown) => T }
| { assert: (input: unknown) => asserts value is T }
| { validateSync: (input: unknown) => T }
| { (input: unknown): Promise<T> | T }
Custom
declo-config.ts
.data({
schema: (data) => {
if (typeof data !== 'object') {
throw new Error('Data must be an object')
}
if (typeof data.name !== 'string') {
throw new Error('Name must be a string')
}
return data
}
})
Zod
declo-config.ts
import { z } from 'zod'
import { DecloConfig } from "@declo/config"
DecloConfig()
.data({
schema: z.object({
name: z.string()
})
})
Yup
declo-config.ts
import * as yup from 'yup'
import { DecloConfig } from "@declo/config"
DecloConfig()
.data({
schema: yup.object({
name: yup.string()
})
})
Valibot
declo-config.ts
import * as v from 'valibot'
import { DecloConfig } from "@declo/config"
DecloConfig()
.data({
schema: v.object({
name: v.string()
})
})
Superstruct
declo-config.ts
import * as ss from 'superstruct'
import { DecloConfig } from "@declo/config"
DecloConfig()
.data({
schema: ss.object({
name: ss.string()
})
})
Default data
You can provide default data that will be used when no data is provided.
declo-config.ts
.data({
defaults: (ctx) => ({
name: "",
})
})