Lingara Lingara 說明文件 學習指南 API 函式庫 App 建立 網頁版
語言: 客家話

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.6

TypeScript

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;
  }
}

這頁包裝个內容