TypeScript
本頁譯自英文。如兩者有出入,以英文頁面為準。 閱讀英文頁面
TypeScript 函式庫是 npm 上的 @lingara/api 套件。它在 Node.js 22 或更新版本上執行,沒有執行期相依套件,並為每個請求、回應和串流事件提供型別定義。
執行環境
它是伺服器端函式庫。它沒有瀏覽器版本,而且當用戶端發現自己身處網頁中時,會拒絕接受用戶端密鑰:放在瀏覽器裡的用戶端密鑰就等於公開的密鑰,任何打開該網頁的人都讀得到。請從你自己的伺服器呼叫 API,只把使用者需要的內容傳給他們。
使用方式
- 每個呼叫都回傳一個 promise。傳入
{ signal }並附上一個AbortSignal即可取消呼叫;此時呼叫會以該 signal 本身的原因被拒絕。 - 串流是一個非同步可迭代物件,以
for await讀取。它是惰性的:請求會在你要求第一個事件時才送出。 - 錯誤繼承自
LingaraError,所以一次instanceof檢查就能捕捉全部四種。當 API 指定了等待時間時,每個錯誤都帶有retryAfter。 - 要使用你自己的 HTTP 堆疊,就在選項中傳入一個
fetch函式。串流的閒置逾時仍然適用。
下面的範例會安裝套件、建立用戶端、以串流方式取得詞彙清單並處理錯誤。
TypeScript
npm install @lingara/api@0.1.0-alpha.6TypeScript
import { Lingara } from "@lingara/api";
const client = new Lingara({
clientId: process.env.LINGARA_CLIENT_ID!,
clientSecret: process.env.LINGARA_CLIENT_SECRET!,
});TypeScript
const stream = client.generateVocabulary({ level: 2, source_lang: "en", target_lang: "zh", count: 8 });
for await (const ev of stream) {
if (ev.event === "item") console.log(ev.data.word, ev.data.translation);
}TypeScript
import { ApiError, MaintenanceError, OAuthError, TransportError } from "@lingara/api";
try {
await client.getUsage();
} catch (e) {
if (e instanceof ApiError) {
// A refusal from the API: e.status, e.code (stable) and e.message (localised).
console.error(e.status, e.code, e.message, e.retryAfter ?? "");
} else if (e instanceof OAuthError) {
// The token endpoint refused the credentials or the scopes.
console.error(e.status, e.error, e.description ?? "");
} else if (e instanceof MaintenanceError) {
console.error("under maintenance; retry after", e.retryAfter ?? "a while");
} else if (e instanceof TransportError) {
// No usable answer: connect, tls, reset, timeout, and so on.
console.error("transport:", e.kind);
} else {
throw e;
}
}