1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Day4] TypeScript × Node.jsで簡単なRESTAPI作ってみる(Class編)

Last updated at Posted at 2018-09-15

進捗状況

TypeScriptでClassを書く

やってることはDay1と同じ

server.ts

import * as express     from "express";     // require("express")
import * as helmet      from "helmet";      // require("helmet")
import * as bodyParser  from "body-parser"; // require("body-parser")

export class MyServer {
  private server: any;    // expressのインスタンス
  private port:   number; // port保管

  constructor() {
    this.server = express();   // インスタンス生成
    this.server.use(helmet()); // セキュリティをhelmetで管理
    this.server.use(bodyParser.urlencoded({ extended: true})); // URLエンコードしてくれる
    this.server.use(bodyParser.json()); // JSON.parse()してくれる
  }

  addRouter(route: any) {
    this.server.use(route); // express.Router()を追加
  }

  start(port: number) {
    this.port = port;
    this.server.listen(this.port); // listen開始
  }
}

router/test.ts

import * as express from "express";

export class TestRouter {
  private router: any;
  constructor() {
    this.router = express.Router();
    this.router.get('/', this.callback);
  }

  callback(request, response, error) {
    response.end('Hello World');
  }

  getRouter() {
    return this.router;
  }
}

app.ts

import {MyServer} from './server';
import {TestRouter} from './router/test';

var server: MyServer = new MyServer();
var test: TestRouter = new TestRouter();
server.addRouter(test.getRouter());
server.start(3000);

感想

てっきりES6のclassと同じものだと思ってたけど、
変換後はprototypeになってて笑った。

export修飾子書くだけで、
module.exportsしてくれるの強い。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?