JavaScript の ミドルウェアパターン

レベル 5507 打鍵

ミドルウェアパターンはデータの変換やフロー制御を順次行うハンドラーをチェーンします。

JavaScript のコード

// ミドルウェアパターンを実装するPipelineクラス
1class Pipeline {
2 constructor() {
// ミドルウェア関数を格納する配列
3 this.middlewares = [];
4 }
5 use(fn) {
// パイプラインにミドルウェアを追加
6 this.middlewares.push(fn);
// チェーン用にthisを返す
7 return this;
8 }
9 async execute(context) {
// 現在のミドルウェアインデックスを追跡
10 let index = 0;
// 次のミドルウェアを呼び出すnext関数を作成
11 const next = async () => {
// まだミドルウェアがあれば実行
12 if (index < this.middlewares.length) {
// 現在のミドルウェアを実行してindexを進め、チェーンを続けられるようnextを渡す
13 await this.middlewares[index++](context, next);
14 }
15 };
// ミドルウェアチェーンを開始
16 await next();
// 変更されたコンテキストを返す
17 return context;
18 }
19}
20
// パイプラインインスタンスを作成
21const pipeline = new Pipeline();
// ミドルウェアを追加
22pipeline
// 1つ目のミドルウェアはctx.a = 1にしてからnextを呼ぶ
23 .use(async (ctx, next) => { ctx.a = 1; await next(); })
// 2つ目のミドルウェアはctx.b = ctx.a + 1 = 2にする
24 .use(async (ctx, next) => { ctx.b = ctx.a + 1; await next(); });
25
// 実行して結果をログ: { a: 1, b: 2 }
26pipeline.execute({}).then(console.log);

実行結果

{ a: 1, b: 2 }
このコードでタイピング練習する

このコードでタイピング練習ができます。記録はランキングに反映されません。

このコードで使う記号

この JavaScript のコードで打つ記号と、出てくる回数です。

  • (× 17
  • )× 17
  • ;× 15
  • .× 14
  • {× 9
  • }× 9
  • =× 9
  • ,× 3
  • +× 3
  • >× 3

JavaScript のレベル 5 のほかのコード例

← JavaScript タイピング練習のトップへ