@dhelarius/entity-parser
v2.2.0
Published
Parse yours json objects to tsc entities
Downloads
15
Maintainers
Readme
@dhelarius/entity-parser
Parse your json objects to tsc entities, useful to know what data your entities return at compile time
Table of Contents
Installing
Package manager
Using npm:
$ npm install @dhelarius/entity-parser
Using yarn:
$ yarn add @dhelarius/entity-parser
Using pnpm:
$ pnpm add @dhelarius/entity-parser
Once the package is installed, do the necessary imports:
import {Entity, JSONObject, jsonObjectToEntity, jsonObjectToEntities, parse} from '@dhelarius/entity-parser';
Example
If it is necessary to parse the following json object:
const json = {
"id": 1,
"name": "John Doe",
"username": "jdoe",
"email": "[email protected]"
}
First import the Entity interface as follows:
import {Entity} from '@dhelarius/entity-parser';
Then create an entity model:
class UserModel implements Entity {
constructor(
readonly id?: number,
readonly name?: string,
readonly username?: string,
readonly email?: string
) {}
}
To parse the json object do the following:
import {jsonObjectToEntity} from '@dhelarius/entity-parser';
const user: UserModel = jsonObjectToEntity(json, UserModel);
For an array of json objects:
import {jsonObjectToEntities} from '@dhelarius/entity-parser';
const user: UserModel = jsonObjectToEntities(json, UserModel);
When making an api-rest call, for example, the data from the response will be taken and parsed like this:
import {jsonObjectToEntity, parse} from '@dhelarius/entity-parser';
...
someService.get('/users/1').then(response => {
const jsonObject = parse(response);
const user: UserModel = jsonObjectToEntity(jsonObject, UserModel);
});
In case you want to get a list of users:
import {jsonObjectToEntities, parse} from '@dhelarius/entity-parser';
...
someService.get('/users').then(response => {
const jsonObject = parse(response);
const users = jsonObjectToEntities(jsonObject, UserModel);
});