Skip to main content

hapi - batch 批處理路線

Dev
Table of Contents

重新看了 Hapi 作者的一個視頻,發現 Hapi 有個很屌的功能,就是它有批處理的端點。

GET    /user/1
GET    /user/2
GET    /user/3
GET    /widget/2342534
GET    /widget/4232415

上面的 HTTP request,平常的你就會發出 5 個請求。蜂窩網絡的世界,每個請求都會很“貴”。Hapi 里則有個 /batch 的端點(通過 bassmaster 插件),把上面五個請求合并到一個,然後 POST 到 /batch

例子
#

POST 下面的資料到 /batch

{ "requests": [
    {"method": "get", "path": "/user/1"},
    {"method": "get", "path": "/user/2"},
    {"method": "get", "path": "/user/3"},
    {"method": "get", "path": "/widget/2342534"},
    {"method": "get", "path": "/widget/4232415"}
] }

伺服器就會解析請求,内部處理這五個 GET,再把回复合并一個 Array。

返回的資料
#

[
  { userId: "1", username: "apple" },
  { userId: "2", username: "boy" },
  { userId: "3", username: "car" },
  { widgetId: "2342534", data: "...." },
  { widgetId: "4232415", data: "...." },
];

取得用戶 ID

// ES5
console.log(data[0].userId);

// ES6 的 “Destructuring assignment”
let [user1, user2, user3, ...widgets] = responseArray;

console.log(user1.userId);

bassmaster 支持流水線請求,從上一個詢查在下一個使用它

{ "requests": [
    {"method": "get", "path": "/currentuser"},
    {"method": "get", "path": "/users/$0.id/profile"}
] }

關於配置:默認的路徑是 /batch,可以配置成其它的路徑。也可以添加用戶認證。

我覺得這個功能對 SPA 應用的也很實用。

官網:覺得實用嗎? 前往插件官網 bassmaster 的 repo