1.1.0 • Published 4 years ago

@taedr/jsontoclass v1.1.0

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
4 years ago

Note that API is on the prototype stage and can be changed dramatically without backward compatibility support!

Documentation

Overview

JsonToClass (JTC) is a JavaScript library for data validation. JTC main purpose is to ensure that expectable and received data are aligned fully. Library provides functionality for converting JS objects into class instances with syntax and semantic validation and gives full description in case of problems.

When to use?

JTC can be very helpful when working with data sources beyond control, like server API or local storage on client side and client request on server side.

Example

Valid

import { JTC } from '@taedr/jsontoclass';

class User {
   public id: number;
   public name: string;

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

const USER_META = new ObjectMeta({
   builder: User,
   fields: {
      id: new NumberField(),
      name: new StringField({ minLength: 3 }),
      sayHi: new FunctionField(),
   }
});

const users = [
   { id: 1, name: `Vasya` },
   { id: 2, name: `Petya` },
   { id: 3, name: `Masha` },
];

const result = JTC.convert({
   id: `Users`,
   meta: new ObjectArrayMeta({ meta: USER_META }),
   values: users,
});

console.log(result.converted.all);

for (const user of result.converted.all) {
   user.sayHi();
}

Corrupted

import { JTC } from '@taedr/jsontoclass';

class User {
   public id: number;
   public name: string;

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

const USER_META = new ObjectMeta({
   builder: User,
   fields: {
      id: new NumberField(),
      name: new StringField({ minLength: 3 }),
      sayHi: new FunctionField(),
   }
});

const users = [
   { id: 1, name: `Vasya` },
   { id: `2`, name: 132 },
   null,
   { id: 3, name: `Petya` },
   { id: `3`, name: `Masha` },
   { id: 4, name: `Ib` },
];

const result = JTC.convert({
   id: `Users`,
   meta: new ObjectArrayMeta({ meta: USER_META }),
   values: users,
});

console.log(result.converted.all);
console.log(result.converted.corrupted);
console.log(result.converted.valid);

for (const user of result.converted.all) {
   user.sayHi();
}

/*
2 -> null | Members can only be of "object" type, but got "null"
1 (EXCLUDED) -> {...} | Validation failed for all fields
1 (EXCLUDED) -> id -> 2 | Expected number, but got string
1 (EXCLUDED) -> name -> 132 | Expected string, but got number
4 (2) -> id -> 3 | Expected number, but got string
5 (3) -> name -> Ib | Length(2) is less than expected(3)
*/
console.log(JTC.log.asString(result.tree));
1.1.0

4 years ago

1.0.0

4 years ago

0.0.32

5 years ago

0.0.33

5 years ago

0.0.34

5 years ago

0.0.30

5 years ago

0.0.29

5 years ago

0.0.25

5 years ago

0.0.26

5 years ago

0.0.21

5 years ago

0.0.20

5 years ago

0.0.19

5 years ago

0.0.18

6 years ago