在前面的章節中,我們學會了如何建立自己的 API,也學過如何使用 **第三方 API(例如 GitHub API)。**那麼如果一個應用程式需要 同時使用多個 API ,應該如何設計呢?這時候,就會用到 Aggregator Pattern(聚合模式) 。
Aggregator Pattern 的核心概念是:
建立一個「中間層 API」,負責呼叫多個後端 API,並將結果整合後回傳給客戶端。
好處是:
假設我們有一個 Todo 應用程式:
{
"todo": {
"id": 1,
"title": "完成 API 教學",
"completed": false
},
"author": {
"login": "octocat",
"name": "The Octocat",
"public_repos": 8
}
}
npm install node-fetch
import express from "express";
import fetch from "node-fetch";
const app = express();
// 假設本地有一個 Todo API
const TODO_API = "http://localhost:3000/todos/1";
const GITHUB_API = "https://api.github.com/users/octocat";
app.get("/aggregated", async (req, res) => {
try {
// 並行請求兩個 API
const [todoRes, githubRes] = await Promise.all([
fetch(TODO_API),
fetch(GITHUB_API)
]);
const todo = await todoRes.json();
const author = await githubRes.json();
res.json({
todo,
author: {
login: author.login,
name: author.name,
public_repos: author.public_repos
}
});
} catch (error) {
res.status(500).json({ error: "Aggregator API Failed" });
}
});
app.listen(4000, () => {
console.log("Aggregator API running on http://localhost:4000");
});
現在,客戶端只要呼叫:
GET http://localhost:4000/aggregated
就能同時拿到 Todo 與 GitHub 使用者的資料。