Kuzunoha-NEのブログ

プログラミングなどの勉強をしてます

【TypeScript】ExpressとApplicationFactory

こんばんは葛の葉です。

さて、ExpressでApplicationFactoryを作りましょう。

以前Flaskで作ったようなものを作成します。

kuzunoha-ne.hateblo.jp

version

express == 4.17.1

プログラム

ディレクトリはこんな感じなのだ

.
├── app.ts
└── factory.ts

Expressのアプリケーションを生成するcreateApp関数を作る。

// factory.ts
import * as express from "express";
import * as bodyParser from "body-parser";

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

createAppをexportしてappを作成する。

// app.ts

import {createApp} from './factory'

const app = createApp();

app.listen(8888, ()=>{
    console.log('こんにちは');
})

コンパイルして実行する。

$ npx ts-node app.ts 
こんにちは
// 別のBashで
$ curl 127.0.0.1:8888/
はろわ

ルーティングを別に作成する。

Express.Routerでルート用プログラムを作る。

// ./controllers/test.ts
import * as express from "express";

const testRouter = express.Router();

testRouter.get('/', function (req, res) {
    res.send('へるごー')
})

export default testRouter;

factory.tsに読み込ませる

// factory.ts
import * as express from "express";
import * as bodyParser from "body-parser";

import testRouter from "./controllers/test"

export function createApp(){
    const app = express();
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use('/test', testRouter);
    return app
}

curlする

$ curl 127.0.0.1:8888/test
へるごー