Does Typebox support Transformation of a QueryParamString to a Record? #878
Unanswered
FoxMessenger
asked this question in
Q&A
Replies: 1 comment
-
@FoxMessenger Hi, Try the following import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
// --------------------------------------------------------
// JsonValue Types
// --------------------------------------------------------
export type JsonValue = JsonObject | JsonArray | JsonString | JsonNumber | JsonBoolean | JsonNull
export interface JsonObject { [key: string] : JsonValue }
export type JsonArray = JsonValue[]
export type JsonString = string
export type JsonNumber = number
export type JsonBoolean = boolean
export type JsonNull = null
// --------------------------------------------------------
// JsonString: Decodes Strings into JsonValue
// --------------------------------------------------------
const JsonString = Type.Transform(Type.String())
.Decode(value => JSON.parse(value) as JsonValue) // todo: Optionally check parsed value. If the value is
.Encode(value => JSON.stringify(value)) // invalid, you can throw inside the Decode func.
// --------------------------------------------------------
// Usage
// --------------------------------------------------------
const T = Type.Object({
Key: JsonString
})
const D = Value.Decode(T, { Key: '{ "key": 12345 }' })
const E = Value.Encode(T, D)
console.log(D) // { Key: { key: 12345 } }
console.log(E) // { Key: '{"key":12345}' } However, just keep in mind it might be better to parse the query string parameter into a JS value "before" passing it to decode (rather than implementing a parser inside the transform). This would be typical for server frameworks as they usually parse URL query strings into untyped JS objects before passing to route handlers. In this respect, you would just write a TB type to check the parsed query string provided by a framework rather than handling query string parsing inside a TB transform....this would be a much simpler approach. Hope this helps |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
How would you type out a Record from a JSON object,
"K": "{\"k\":v}"
?Transform().Decode().Encode() seems to be the correct direction, but there wasn't enough information in that section for me to correctly create the right mapping. Could anyone provide the best approach to take?
Beta Was this translation helpful? Give feedback.
All reactions