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

allow custom data types to specify serialize function #122

Open
ahdinosaur opened this issue Dec 28, 2014 · 3 comments
Open

allow custom data types to specify serialize function #122

ahdinosaur opened this issue Dec 28, 2014 · 3 comments

Comments

@ahdinosaur
Copy link

hey 😄, i think it would be great if we could specify serialize functions for our custom data types.

my use case is for using big.js decimals as a custom data type where the representation as an object is not how i want the object serialized. i could write a custom serialize function for my model, but it seems like this information should be part of the data type definition.

how do we feel about this?

@latentflip
Copy link
Contributor

So, this may change, but right now the way this is done for dates for example, is to store the serialized representation in the state object, and to reconvert it in the getter. serialize() on the state object will grab that internal representation.

So, date looks like (slightly simplified)

date: {
  set: function (newVal) {
    return {
      type: 'date',
      val: newVal.valueOf() //integer representing the date
    };
  },
  get: function (val) {
    return new Date(val);
  }
}

So, for big.js you could do something similar

decimal: {
  set: function (newVal) {
    if (newVal instanceof Big) {
      return {
        type: 'decimal',
        val: newVal.toF()
      };
    } else {
      return {
        type: typeof newVal,
        val: newVal
      }
    }
  },
  set: function (val) {
    return new Big(val);
  }
}

I think that should work, even if it's not the most obvious solution. I'm currently thinking about how all this datatype stuff works, and whether we can improve it, so thouhts welcomed! :)

@ahdinosaur
Copy link
Author

thanks @latentflip, your solution works great. 😸 i'll see if i run into anything as i use it, but for now this pattern is what i needed.

cheers, 🍧

@ianwremmel
Copy link

I'd also like to see serialize() (and maybe deserialize()) separate from get (and set). I'm running into an issue where I want my client code to use Date objects, but my server only accepts ISODate strings. I can deal with it by overriding State#serialize(), but it feels more elegant to do it in State#dataTypes.

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

No branches or pull requests

4 participants