General

In order to be able to perform JTC.convert you will need meta info about fields in expected data. Such info can be got with JTC.createMeta

const APP_INFO = Symbol(`APP_INFO`);

class AppInfo {
   public isSelected: boolean;
}

class Id {
   public id: string;
}

const ID_META = new ObjectMeta({
   builder: Id,
   getId: ({ id }) => id,
   fields: {
      id: new StringField(),
   }
});

class User extends Id {
   public name: string;

   public get short() { return `${this.id} - ${this.name}`; }

   public sayHi() {
      console.log(`Hi! My name is ${this.name}`);
   }

   public [APP_INFO]: AppInfo;
}

const USER_META = new ObjectMeta({
   builder: User,
   fields: {
      id: new StringField(),
      name: new StringField(),
      short: new StringField({ isCalculated: true }),
      sayHi: new FunctionField(),
      [APP_INFO]: () => new AppInfo(),
   }
});

console.log(USER_META);

USER_META.validate({
   value: new User()
})

/* class builder provided in ctx */
USER_META.builder
console.log(USER_META.builder === User); // true
/* Shortcut to builder name */
USER_META.id
console.log(USER_META.id === USER_META.builder.name); // true
/* Map of all fields defined under string keys */
USER_META.fields.strings
console.log([...USER_META.fields.strings.keys()]); // ['id', 'name', 'short', 'sayHi']
/*  Map of iterable fields, includes fields defined under string keys,
excludes function and field marked as "isCalculated: true". This map will
be used during conversion (JTC.convert) and deconversion (JTC.deconvert)
*/
USER_META.fields.iterables;
console.log([...USER_META.fields.iterables.keys()]); // ['id', 'name']
/* Map of symbols with corresponding initializers */
USER_META.fields.symbols
console.log([...USER_META.fields.symbols.keys()]); // [ Symbol(APP_INFO) ]
/* Meta info about direct class parrent in case of inheritance */
USER_META.parrent
console.log(USER_META.parrent === ID_META); // true
/* Id getter provided in ctx, if not can be inherietd from parrents */
USER_META.getId
console.log(USER_META.getId === ID_META.getId); // true
/* Type checker provided in ctx */
USER_META.isOfType
console.log(USER_META.isOfType === undefined); // true
/* Method for class instance validation */
USER_META.validate

Last updated

Was this helpful?