Giter VIP home page Giter VIP logo

serialazy's People

Contributors

dependabot[bot] avatar teq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

serialazy's Issues

example for TypeSerializer<TSerialized, TOriginal> optional properties?

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

Support `options` for custom serializers

Default serializers can accept options parameter:

@Serialize(/*options=*/{ nullable: true })

Custom serializers should support it too. E.g.:

@Serialize.Custom(/*serializer=*/{...}, /*options=*/{ nullable: true })

lost inheritance

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:

Code:

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);

Output:

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.

Support non-JSON serialization backends

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.

Recursive serialization with optional properties

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.

Support "projections"

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.

Support class inheritance

  • Child class should inherit all property serializers from parent classes.
  • Serializers from a child class should be able to "shadow" ones from parent
  • Serializer should be "tied" to a property of a class where it was defined, but not to properties with the same name of clild/parent classes. E.g., 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. Not possible because there is no way to identify from which class of inheritance chain property came from.

Custom serialization for enum type

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

  • Moved code to Gist
  • Support string enums
  • Override standard methods 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).
  • Add unit tests (Jest).

Jan-03-2020

  • Made the decorator function typesafe:
    • A compile error gets raised if the 'value' property of the wrapper class is of a different enum type than what is passed to the decorator function.
    • When the valuesDescriptor option is specified, ist must have a property for each enum key. Otherwise a compile error gets raised.

down / up -> deflate / inflate

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 !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.