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

Type coercion in JSON serialization #148

Open
stevenschobert opened this issue Mar 28, 2018 · 0 comments
Open

Type coercion in JSON serialization #148

stevenschobert opened this issue Mar 28, 2018 · 0 comments
Milestone

Comments

@stevenschobert
Copy link
Contributor

stevenschobert commented Mar 28, 2018

When working with models toJson and fromJson serializers, there is inconsistent behavior when it comes to the typed fields.

The model itself gets returned as a standard Object, but the model's fields preserve their original type.

In cases where you the field is one of the standard types (string, number, etc.), this isn't a problem.

The problem arrises when you deal with types like:

  • Date
  • ObjectID
  • other models
  • etc.

All these types will end up being converted to some other type by JSON.stringify, but I believe the developer experience will be more consistent if this conversion happens at the model level.

Example of Problem

// example model
@Model()
class Tweet extends SapiModelMixin() {
  @Json()
  content: string;
  @Json()
  postedDate: Date;
}

// example instance
let t = new Tweet();
t.content = "Hello world!";
t.postedDate = new Date();
await t.save();

// serialize to json does not convert types
let json = t.toJson();
console.log(typeof json.postedDate); // => Date
console.log(typeof json.id); // => ObjectID

// serialize from json does not convert types
let newTweet = Tweet.fromJSON({
  content: "hello 2",
  postedDate: "2018-03-28T20:24:13.960Z"
});
console.log(typeof newTweet.postedDate); // => string

Notes

If we decided to have the toJson and fromJson serialization do type conversion, we might have a convenient place to place some other conveniences, namely to support TypeScript's enum type, and serialize that to the enums string name.

@etsuo etsuo added this to the 0.12.0 milestone Mar 28, 2018
@etsuo etsuo modified the milestones: 0.12.0, 0.13.0 Apr 5, 2018
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

2 participants