Typescript + Decorator + Express 라이브러리 소개

PADA·2019년 4월 12일
0
post-thumbnail

본 라이브러리는 decorator를 이용해 express의 몇몇 기능을 쉽게 작성할 수 있도록 도와주는 라이브러리입니다.

라이브러리 코어 기능

  1. decorator를 이용해 application level의 middleware를 지정한다.
  2. decorator를 이용해 router level의 middleware를 지정한다.
  3. decorator를 이용해 router request parameter 중 필수 값을 지정한다.
  4. decorator를 이용해 router method를 만든다.

기능 설명 및 코드

application

//./app.ts

// 만들어진 라우터들을 수입한다
import './src/controllers';
import { TypadaExpressInstance } from "ts-decorator-express";
import * as Express from 'express';

// 라이브러리를 통해 만들어진 Express application을 사용한다. 
// Express application을 생성할 때 미들웨어를 배열로 넘겨주면 미들웨어가 적용된 express application이 리턴된다.
// 리턴된 express application은 proxy로 감싸져 나온 객체이므로 express application의 모든 기능을 온전히 사용할 순 없다.

const app = TypadaExpressInstance.createInstance([
    Express.json(), Express.urlencoded({ extended: true }),
]);


// 여느때와 같이 3000번 포트를 리슨한다
app.listen(3000, () => {
    console.log('Typada Express Decorator Start, ', 3000);
});

router

// ./src/controllers/user

import { Controller, Get, Required } from "ts-decorator-express";
import { middle1, middle2, middle3 } from "../middlewares";

// 만든 User 클래스를 라우터로 생성한다. application 생성할 때와 마찬가지로 미들웨어를 넘겨주면 미들웨어가 적용되서 라우터가 생선된다.
// router의 path는 현재 http://localhost:3000/users 이다.
@Controller('/users', middle1, middle2, middle3)
export class User {
    // 라우터에 GET 메소드를 생성한다. application, router 생성할 때와 마찬가지로 미들웨어를 넘겨주면 미들웨어가 적용되서 router get이 생성된다.
    // 이 메소드의 path는 GET 현재 http://localhost:3000/users 이다.
    @Get('', middle1, middle2 ,middle3)
    async getUsers(req, res, next) {
        try {
            console.log('get Users')
            return res.status(200).json({
                status:200
            })
        } catch (error) {
            console.log(error);
        }
    }
    
    // 라우터에 POST 메소드를 생성한다. application, router 생성할 때와 마찬가지로 미들웨어를 넘겨주면 미들웨어가 적용되서 router post가 생성된다.
    // 이 메소드 path는 현재 POST http://localhost:3000/users 이다.
    // 요청값에 Required decorator가 있다. 이 decorator는 POST http://localhost:3000/users로 요청할 때 body값에 id을 필수값으로 지정하는 decorator다. 만약 요청 바디에 id가 없으면 에러가 발생한다.
    @Post('')
    async createUser(Required('body', ['id']) req, res, next) {
        try {
            console.log('create User')
            return res.status(200).json({
                status:200
            })
        } catch (error) {
            console.log(error);
        }
    }
    // 라우터에 GET 메소드를 생성한다. application, router 생성할 때와 마찬가지로 미들웨어를 넘겨주면 미들웨어가 적용되서 router get이 생성된다.
    // 이 메소드 path는 현재 get http://localhost:3000/users/:id?name= 이다.
    // 요청값에 Required decorator가 있다. 이 decorator는 get http://localhost:3000/users로 요청할 때 querystring값에 name을 필수값으로 지정하는 decorator다. 만약 요청 querystring에 name이 없으면 에러가 발생한다.
    @Get(':id')
    async createUser(Required('query', ['name']) req, res, next) {
        try {
            console.log('get User')
            return res.status(200).json({
                status:200
            })
        } catch (error) {
            console.log(error);
        }
    }
}

index

// ./src/controllers/index

// 만든 라우터를 수입한다.
import './user';

결론

  • 기존 expressjs를 쓸 때 했던 라우팅 등록 일들이 줄어 들어 편하다.
  • 그러나 express의 온전한 기능들을 전부 사용할 수 없다. 예를 들어 router의 기능은 routing(get, post, patch ..)에 있지만 그 외 사용하는 다른 함수와 프로퍼티는 사용하지 못한다. 추가로 app도 마찬가지이다.
  • 만약 사용하는 프로젝트에서 router 또는 app에 기능을 많이 사용하지 않는다면 써봐도 좋을 것 같다.

Link

https://www.npmjs.com/package/ts-decorator-express

profile
padalog 쥬니어

1개의 댓글