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