项目作者: EnzoDiazDev

项目描述 :
Instance to JSON, JSON to instance
高级语言: TypeScript
项目地址: git://github.com/EnzoDiazDev/ijji.git
创建时间: 2021-02-23T20:25:27Z
项目社区:https://github.com/EnzoDiazDev/ijji

开源协议:MIT License

下载


ijji

From: Instance to JSON, JSON to Instance (pronounced like e-hee)

is a library that provides a couple of functions to convert class instances to json, and json to class instances. Ah, it also offers a couple of types for typing like a champion.

run:

npm i enzodiazdev@ijji

Super simple example

  1. import {json_to_instance, instance_to_json} from "@enzodiazdev/ijji";
  2. class Person {
  3. public name:string
  4. constructor(name:string){
  5. this.name = name;
  6. }
  7. public hi():void {
  8. console.log("hi!");
  9. }
  10. }
  11. const lottie = new Person("lottie");
  12. lottie.hi(); // "hi!"
  13. database.write( instance_to_json(lottie) );
  14. const john_data = database.get("john");
  15. john_data.hi(); // ERROR, 'hi()' is not a function
  16. const john = json_to_instance(john_data, Person);
  17. john_data.hi(); // "hi!"
  18. //ERROR: {name:number, age: string} does not match Person.
  19. const pepe = json_to_instance({name:10, age:"0"}, Person)

you can also:

  1. import {PropertiesOf} from "@enzodiazdev/ijji";
  2. const john_data:PropertiesOf<Person> = database.get("john");

In your own class

  1. import {instance_to_json, PropertiesOf} from "@enzodiazdev/ijji";
  2. class Person {
  3. public name:string
  4. constructor(name:string){
  5. this.name = name;
  6. }
  7. public hi():void {
  8. console.log("hi!");
  9. }
  10. public to_json():PropertiesOf<this> {
  11. return instance_to_json(this);
  12. }
  13. }

That’s all.