Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q: Is Measure serialisation / deserialisation possible? #203

Open
aethr opened this issue Sep 16, 2024 · 0 comments
Open

Q: Is Measure serialisation / deserialisation possible? #203

aethr opened this issue Sep 16, 2024 · 0 comments

Comments

@aethr
Copy link
Contributor

aethr commented Sep 16, 2024

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 simpler

I'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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant