@agilearchitects/dto-maker
v0.0.6
Published
The DTO Maker servers two purposes: - Generate schema from DTO interface - parse (and validate) object as DTO interface according to provided schema
Downloads
26
Readme
DTO-Maker
The DTO Maker servers two purposes:
- Generate schema from DTO interface
- parse (and validate) object as DTO interface according to provided schema
Requirements:
- Typescript
Generate schema
Use the createSchemaFromInterface
method to return a json object of an interface. Path to interface file and its name is required.
Given: ./dto/hello-world.dto.ts
:
/* Description of interface */
export interface IHelloWorldDTO {
/* Object ID */
id: number;
name: string;
// Description is optional
description?: string;
}
...using...
import ts from "ts";
const schema = createSchemaFromInterface(
"./dto/hello-world.dto.ts",
"IHelloWorldDTO",
ts,
);
console.log(schema);
Will output:
{
"name": "IHelloWorldDTO",
"description": "Description of interface",
"properties": [
{
"name": "id",
"description": "Object ID",
"type": "number"
},
{
"name": "name",
"type": "string"
},
{
"name": "description",
"description": "Description is optional",
"type": "string",
"optional": true
}
]
}
Method supports array types and complex types (like reference to other interfaces).
Parse DTO object using schema
Using the above schema an object can be parsed as interface using the parseDTOFromJson
method.
parseDTOFromJson([schema], {
id: 1,
name: "MyName",
description: "",
}, "IHelloWorldDTO");
The method will throw an error if object does not fit schema. Error message tries to be as descriptive as possible
Working with multiple interfaces
If an interface reference another interface, schema for that interface must be provided as well when trying to parse.
Example:
Given: another.dto.ts
:
export interface IAnotherDTO {
id: number;
tags: string[];
}
...and hello-world.dto.ts
:
export interface IHelloWorldDTO {
id: number;
name: string;
description?: string;
another: IAnotherDTO;
}
...using...
import ts from "ts";
// Generate schemas for interfaces
const schemas = [
createSchemaFromInterface(
"./dto/hello-world.dto.ts",
"IHelloWorldDTO",
ts,
),
createSchemaFromInterface(
"./dto/another.dto.ts",
"IAnotherDTO",
ts,
),
];
// Parse object using schemas
parseDTOFromJson(schemas, {
id: 1,
name: "MyName",
description: "",
another: {
id: 1,
tags: ["a", "b", "c"]
}
}, "IHelloWorldDTO");
Anecdote
The lib was written to easier parse JSON-objects coming from HTTP requests without needing to write individual parser for each DTO interface.
A great way of using this lib is to create a npm/yarn command for generating schemas for all your DTO interfaces into a big json schema file. Later this file can be referenced any time you wanna parse a json object coming from a HTTP response.
Remember that this only helps casting the object and has no way of validating data. It only checks data type.