A
arktype2mo ago
GreggOD

empty string now but length string later?

For a few of my schemas i have them setup like this, which means the values can be empty string:
export const telephone = type({
international: "string",
"local?": "string",
"readable?": "string"
})
export const telephone = type({
international: "string",
"local?": "string",
"readable?": "string"
})
But there are cases where I want to ensure the values are filled in, is there a way with arktype to specify that I want a schema to expect a value?
// i want this to throw an error because i expect the international field to be present
telephone.from({
international: ""
})
// i want this to throw an error because i expect the international field to be present
telephone.from({
international: ""
})
This is something that I run into a lot where the initial values stored into the DB are empty strings but when the data is updated via some controller i need to ensure the values are passed in. I dont want to duplicate all my schemas. Any recommendations?
1 Reply
ssalbdivad
ssalbdivad2mo ago
The best way to handle a transform like this would be a custom wrapper. Here's an example of how you could implement it:
import { type } from "arktype"

function withNonEmptyStrings<t extends type.Any<object>>(t: t): t
function withNonEmptyStrings(t: type<Record<string, unknown>>) {
return t.map(prop => {
const stringValue = prop.value.ifExtends(type.string)
if (!stringValue) return prop

return {
...prop,
value: stringValue.atLeastLength({
rule: 1,
"meta.message": "custom message"
})
}
})
}

export const telephone = type({
international: "string",
"local?": "string",
"readable?": "string"
})

const nonEmptyTelephone = withNonEmptyStrings(telephone)

// ArkErrors: custom message
nonEmptyTelephone.from({
international: ""
})
import { type } from "arktype"

function withNonEmptyStrings<t extends type.Any<object>>(t: t): t
function withNonEmptyStrings(t: type<Record<string, unknown>>) {
return t.map(prop => {
const stringValue = prop.value.ifExtends(type.string)
if (!stringValue) return prop

return {
...prop,
value: stringValue.atLeastLength({
rule: 1,
"meta.message": "custom message"
})
}
})
}

export const telephone = type({
international: "string",
"local?": "string",
"readable?": "string"
})

const nonEmptyTelephone = withNonEmptyStrings(telephone)

// ArkErrors: custom message
nonEmptyTelephone.from({
international: ""
})
You could extend that map call to apply other custom transforms depending on the value type

Did you find this page helpful?