Advertisement
Guest User

Deserialize using TypeScript property decorators

a guest
Jun 26th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. deserialize.ts
  2. --------------------
  3.  
  4. import 'reflect-metadata';
  5.  
  6. export const Metadata: any = {};
  7.  
  8. export function Expose(target: any, key: string) {
  9.   const type = Reflect.getMetadata('design:type', target, key);
  10.   if (!Metadata[target.constructor.name]) {
  11.     Metadata[target.constructor.name] = {};
  12.   }
  13.   Metadata[target.constructor.name][key] = type;
  14. }
  15.  
  16. export class Deserializable {
  17.   deserialize(input: object): this {
  18.     Object.keys(Metadata[this.constructor.name]).forEach(key => {
  19.       this[key] = input[key] || Metadata[this.constructor.name][key]();
  20.     });
  21.     return this;
  22.   }
  23. }
  24.  
  25. Page.model.ts
  26. --------------------
  27.  
  28. import { Expose, Deserializable } from './deserialize';
  29.  
  30. export class Page extends Deserializable {
  31.   @Expose content: object;
  32.   @Expose date: string;
  33.   @Expose id: number;
  34.   @Expose slug: string;
  35.   @Expose title: object;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement