teq / serialazy Goto Github PK
View Code? Open in Web Editor NEWTypeScript class serialization / data-mapping library
Home Page: https://serialazy.teqlab.net
License: MIT License
TypeScript class serialization / data-mapping library
Home Page: https://serialazy.teqlab.net
License: MIT License
class Topping {
@Serialize() public type: string;
}
class Book {
@Serialize() public name: string;
@Serialize() public topping: Topping[];
}
I tried and see it doesn't work.
I have looked into the source code and curious of how did implemented it. It shows that you really have very good understanding and experience of OOP.
I really want to learn it, can you take time to explain me?
It will be great if you can give me your email or skype.
Thanks!
Hello,
is there any example for using @Serialize.Custom with this optinal properties in the TypeSerializer<TSerialized, TOriginal> interface?
/**
* _Optional._ Original type constructor function.
* Default: Value of `design:type` for given property.
*/
type?: Constructable.Default<TOriginal>;
/**
* _Optional._ Property type descriminator function.
* Used to narrow type constructor function (e.g. for union types)
* @param serialized Serialized value
* @returns Original type constructor function
*/
discriminate?(this: void, serialized: TSerialized): Constructable.Default<TOriginal>;
I google the code go in deep for the inflate and deflate function and can not even find, that this two properties are used. I want to use the discriminate function to map the name of a type, stored in a serialized string property to a type via a "typemapper".
Thanks for help!
Georg
Default serializers can accept options
parameter:
@Serialize(/*options=*/{ nullable: true })
Custom serializers should support it too. E.g.:
@Serialize.Custom(/*serializer=*/{...}, /*options=*/{ nullable: true })
Hello,
I have a class model, where i was able to put mutch of the properties in the base class an only in part of the cases a have to add properties but make descisions on the type. But serialazy lost the type if there are no properties in the chain or none of the properties are serialized. Example:
class Person {
@serialize({ optional: true }) public Name?: string;
@serialize({ optional: true }) public Surname?: string;
}
class Employer extends Person {
public Unit?: string;
}
const employer = new Employer();
employer.Name = "Dug";
employer.Surname ="Donald";
employer.Unit = "Finance";
console.log(employer);
const deflatedEmployer = deflate(employer);
console.log(deflatedEmployer);
const inflatedEmployer = inflate(Employer, deflatedEmployer);
console.log(inflatedEmployer);
Employer {Name: "Dug", Surname: "Donald", Unit: "Finance"}
AppSession.ts:76
[[StableObjectId]]:5
Name:"Dug"
Surname:"Donald"
Unit:"Finance"
proto:Person {constructor: }
Object {Name: "Dug", Surname: "Donald"}
AppSession.ts:79
[[StableObjectId]]:9
Name:"Dug"
Surname:"Donald"
proto:Object {constructor: , defineGetter: , defineSetter: , …}
Person {Name: "Dug", Surname: "Donald"}
AppSession.ts:82
[[StableObjectId]]:12
Name:"Dug"
Surname:"Donald"
proto:Object {constructor: }
I would expect, that inflate returns "Employer" as class with undefiend for the propertie "Unit", but the function returns "Person". If "Employer" yust extends "Person" with no properties lead to steh same result.
Refactor code to be more generic to be able to use it as a base for other serialization backends (each backend as a separate npm package): MongoDB, SQL (postgres/mysql), protocol buffers, etc.
JSON backend will stay in this package.
Hello,
this modified example will not work:
class Author {
@serialize({ optional: true}) public name?: string;
}
class Book {
@serialize() public title: string;
@serialize({ optional: true}) public author?: Author; // Serializes Author recursively
}
You will get an error like "Cannot read property 'name' of undefined" in case there is no 'author'. There is no difference if you make the 'name' property optional or not. So the up function of the serializer can't handle optional in deep. Propably the down has the same problem.
The main idea behind this is to be able to apply multiple sets of prop serializers (each set identified by projection name
) to the same type and then specify required projection
as an argument for deflate
/inflate
. It is useful when (for example) type has multiple storage formats.
B extends A
, A.x
has a serializer, B
has its own x
without serializer. In this case B.x
should "shadow" A.x
and erase its serializer.I wanted to do something like this to define custom enum serialization (e. g. to serialize enum value as string instead of number):
@Serialize.Type({ ... })
enum MyEnum { a, b, c }
Unfortunately this doesn't work, because TS compiler says "Decorators are not valid here".
As a workaround we can wrap the enum inside a class. Then we can add decorator to the wrapper class. Maybe this is something you want to add to your library?
Here is the code of my TS module (2 files including Jest unit tests):
https://gist.github.com/zett42/bbd427e66cfabe3045ed73761d386a91
Usage example for serialization:
enum BallSizeEnum {
little,
normal,
big,
}
@SerializeEnumWrapper( BallSizeEnum )
// By default, enum is serialized as the string key. To serialize as the value:
//@SerializeEnumWrapper( BallSizeEnum, { serializeAsKey: false } )
class BallSize {
constructor( public value: BallSizeEnum = BallSizeEnum.normal ) {}
}
class Ball {
@Serialize() size: BallSize = new BallSize( BallSizeEnum.big );
}
Usage example for reflection:
(requires TS compiler option emitDecoratorMetadata)
enum BallSizeEnum {
little,
normal,
big,
}
@SerializeEnumWrapper( BallSizeEnum, {
// Add optional meta data per enum key. Values can be anything.
valuesDescriptor: {
little: "Little Ball",
normal: "Normal Ball",
big: { more: "info" },
}
})
class BallSize {
constructor( public value: BallSizeEnum = BallSizeEnum.normal ) {}
}
const ballSize = new BallSize;
console.log( getEnumValuesMetadata( ballSize ) );
// ... prints {0: "little", 1: "normal", 2: "big", little: 0, normal: 1, big: 2}
console.log( getEnumValuesDescriptorMetadata( ballSize ) );
// ... prints {little: "Little Ball", normal: "Normal Ball", big: {…}}
Revisions of this post:
Jan-05-2020
valueOf()
, toString()
and toJSON()
of the prototype of the wrapper class to "unwrap" the native enum value. Add option 'toJsonAsKey' so that toJSON()
writes the key instead of the value (default).Jan-03-2020
Hello,
I just stumbled on this library. Haven't used it (yet !), but something striked me immediately : for the sake of consistency, shouldn't down/up in the custom serializers be named deflate / inflate instead ?
I have been a user of cerialize for quite some time now, but I must say I'm not a big fan of it and am looking for a replacement -- this could be it.
Thank you for your work !
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.