Marshalling
Serializing and deserializing data
Handling arbitrary data
Since everything sent over the wire are basically strings, we can't send anything and get it returned the same. I.e Date
will lose it's structure once converted to string
.
const date = new Date()
// Tue Nov 05 2024 10:58:45 GMT+0100 (Central European Standard Time)
date.toString()
But the server/client both need to know how to convert this string into the expected object.
middleware
// will send date.toString()
.call(() => new Date)
To handle returning/sending any data we can use devalue which SvelteKit already uses.
Devalue option
Fortunately devalue
already takes care of Date
, but here's how we can do it ourselves in a shared options file.
kavi/options.tsimport { createOptions, devalueOption } from 'kavi'
export const options = createOptions({
devalue: {
Date: devalueOption
.stringify((value) => {
if (value instanceof Date) {
return date.toString()
}
})
.parse((value) => new Date(value))
}
})
We have no made sure that both server and client agree on how to handle Date
.