본문 바로가기

Project/TIL

20.03.15 ShareBook TIL

Router Controller 설정

// src/interfaces/controller.interface.ts

import { Router } from 'express';

interface Controller {
  path: string;
  router: Router;
}

export default Controller;

 

// src/routes/users/users.controller.ts

import express, { Request, Response, NextFunction } from 'express';
import Controller from '../../interfaces/controller.interface';
// import express = require('express');

class UsersController implements Controller {
  public path = '/users';

  public router = express.Router();

  constructor() {
    this.initRoutes();
  }

  private initRoutes() {
    this.router.get(`${this.path}`, this.getUsers);
  }

  // eslint-disable-next-line no-unused-vars
  private getUsers = (req: Request, res: Response, _next: NextFunction) => {
    res.status(200).send('Success users');
  };
}

export default UsersController;

 

 

// src/main.ts

import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import cookieParser from 'cookie-parser';

import Controller from './interfaces/controller.interface';
import UsersController from './routes/users/users.controller';
import BooksController from './routes/books/books.controller';
import HistoryController from './routes/history/history.controller';

export default class App {
  // 타입 지정
  public app: express.Application;

  private router: express.Router;

  private path: string;

  constructor(Controllers: Controller[]) {
    // 사용되는 함수들
    this.app = express();
    this.router = express.Router();
    this.path = '/';

    this.initMiddlewares();
    this.initRouter();
    this.initControllers(Controllers);
  }

  public listen() {
    // listen()을 실행하기 위해 public으로 지정
    const PORT: number = Number(process.env.PORT) || 4000;
    this.app.listen(PORT, () => {
      console.log(`Server listen on PORT ${PORT}`);
    });
  }

  private initMiddlewares() {
    // 미들웨어 사용
    this.app.use(cors());
    this.app.use(morgan('dev'));
    this.app.use(bodyParser.json());
    this.app.use(cookieParser());
  }

  private initRouter() {
    this.app.use(this.router);
    this.router.get(`${this.path}`, this.getMain);
  }

  private initControllers(Controllers: Controller[]) {
    Controllers.forEach((controller: Controller) => {
      this.app.use('/', controller.router);
    });
  }

  private getMain = (req: Request, res: Response, next: NextFunction) => {
    res.status(200).send('Server Success!!!!');
  };
}

const app = new App([
  new UsersController(),
]);

app.listen();

 

localhost:4000/users를 만든식으로 /books, /history를 만들었는데 요청 로직을 작성할 예) /users/signup 을 어떻게 또 만들어야하는지는 아직 잘 모르겠다. 

'Project > TIL' 카테고리의 다른 글

20.03.17 ShareBook TIL  (0) 2020.03.18
20.03.16 ShareBook TIL  (0) 2020.03.17
20.03.14 ShareBook TIL  (0) 2020.03.15
20.03.13 ShareBook TIL  (0) 2020.03.13
20.03.12 ShareBook TIL  (0) 2020.03.13