-
Notifications
You must be signed in to change notification settings - Fork 16
Description
While using safe-units in a nuxt project, sometimes nuxt will serialise server-side state and add it to the document as a JSON payload to be deserialised in the client during hydration. Using objects that are class instances (such as Measure) results in an error on the server about non-POJOs (plain old javascript objects):
Cannot stringify arbitrary non-POJOs
Nuxt does provide a capability to add your own serialisation/deserialisation by way of definePayloadPlugin:
// plugins/measurePayload.ts
export default definePayloadPlugin(() => {
definePayloadReducer('Measure', (value) => {
if (Measure.isMeasure(value)) {
// return a plain javascript object with the public properties of a Measure:
// value, unit, unitSystem, symbol
return {
...value,
unitSystem: { ...value.unitSystem },
};
}
});
definePayloadReviver('Measure', (value) => {
const { value, unit, unitSystem, symbol } = value;
const unitInstance = ...; // does safe-units make this possible?
return Measure.of(value, unitInstance);
});
});
// this could also possibly be done individually for Unit and UnitSystem to make each part simplerI'm wondering if it's possible using the current tools provided by the library to construct a Measure class instance from the data available in Measure's public properties (value, unit, unitSystem, symbol)? Since the value is just a number, it seems the hard part is re-constructing an instance of the unit / unit system.
If we were to assume the SIUnitSystem, is there a way to take the unit dimensions (ie { length: 2, mass: 1, ... }) and construct a unit instance from them? Is it safe to use Dimensionless as the unit during de-serialisation? Are the dimensions used in any calculation/conversion, or are they simply there for type checking?
If it's not possible now, but you can see a way to add the capability, is that a useful feature?