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