typed-dto
TypeScript icon, indicating that this package has built-in type declarations

0.1.2-beta.2 • Public • Published

TypedDTO

Strong validated Data Transfer Objects for typescript.

NPM: typed-dto

Installation: npm install typed-dto

Example:

Schema:

./dto/article.dto.ts

import {BaseDTO, Schema, Property} from "typed-dto";

@Schema({strict: true})
class ArticleDTO extends BaseDTO
{
    @Property({ type: "string", regexp: /^[0-9a-zA-Z]{5,256}$/s })
    public title: string;
    
    @Property({ type: "string", min: 5, max: 256*256 })
    public content: string;
    
    @Property({ type: "date" })
    public publishedAt: Date;
}
NestJS Usage:

articles.controller.ts

import { Controller, Post, Body, HttpException } from '@nestjs/common';
import {ArticleDTO} from "./dto/article.dto";

@Controller("articles")
export class ArticlesController
{
    @Post("/create")
    create(@Body() body): string
    {
        const article = ArticleDTO.create(body);
        if(article) // check if not null
            return "OK";
        throw new HttpException("Invalid body.", 400);
    }
}
Express Usage:

app.ts

import * as express from "express";
import * as bodyParser from "body-parser";
import {ArticleDTO} from "./dto/article.dto";

const app = express();
app.use( bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); 

app.post('/articles/create', function(req, res)
{
    const article = ArticleDTO.create(req.body);
    
    if(article) // check if not null
    {
        res.writeHead(200);
        res.end("OK");
    }
    else
    {
        res.writeHead(400);
        res.end("Invalid body.");
    }
});

app.listen(3000);

Package Sidebar

Install

npm i typed-dto

Weekly Downloads

0

Version

0.1.2-beta.2

License

MIT

Unpacked Size

87.3 kB

Total Files

212

Last publish

Collaborators

  • artem-zabolotnyi