# @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](#installing)
- [Example](#example)

# 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:

```javascript
import {Entity, JSONObject, jsonObjectToEntity, jsonObjectToEntities, parse} from '@dhelarius/entity-parser';
```

# Example
If it is necessary to parse the following json object:

```javascript
const json = {
    "id": 1,
    "name": "John Doe",
    "username": "jdoe",
    "email": "jdoe@example.com"
}
```

First import the ***Entity interface*** as follows:
```javascript
import {Entity} from '@dhelarius/entity-parser';
```

Then create an entity model:
```typescript
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:

```typescript
import {jsonObjectToEntity} from '@dhelarius/entity-parser';

const user: UserModel = jsonObjectToEntity(json, UserModel);
```

For an array of json objects:

```typescript
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:

```typescript
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:

```typescript
import {jsonObjectToEntities, parse} from '@dhelarius/entity-parser';

...

someService.get('/users').then(response => {
    const jsonObject = parse(response);
    const users = jsonObjectToEntities(jsonObject, UserModel);
});
```