测试语言TypeScript API库
](https://npmjs.org/package/test-language)
此库提供了从服务器端TypeScript或JavaScript对测试语言REST API的方便访问。
可以在上找到REST API文档 support.launchdarkly.com。此库的完整API可在中找到 api.md.
它是通过以下方式生成的 不锈钢.
安装
npm install git+ssh://git@github.com:stainless-sdks/test-language-typescript.git\[!注意\] 一旦这个包裹 ,这将变成: npm install test-language用法
此库的完整API可在中找到 api.md.
import TestLanguage from 'test-language';
const client = new TestLanguage({
apiKey: process.env['TEST_LANGUAGE_API_KEY'], // This is the default and can be omitted
environment: 'environment_1', // defaults to 'production'
});
async function main() {
const v2s = await client.api.v2.list();
console.log(v2s.links);
}
main();请求和响应类型
此库包含所有请求参数和响应字段的TypeScript定义。您可以这样导入和使用它们:
import TestLanguage from 'test-language';
const client = new TestLanguage({
apiKey: process.env['TEST_LANGUAGE_API_KEY'], // This is the default and can be omitted
environment: 'environment_1', // defaults to 'production'
});
async function main() {
const v2s: TestLanguage.API.V2ListResponse = await client.api.v2.list();
}
main();每个方法、请求参数和响应字段的文档都可以在文档字符串中找到,并将在大多数现代编辑器中悬停显示。
文件上传
与文件上传相对应的请求参数可以以多种不同的形式传递:
File(或具有相同结构的物体)- 一
fetchResponse(或具有相同结构的物体) - 一
fs.ReadStream - 我们的返回值
toFile助手
import fs from 'fs';
import TestLanguage, { toFile } from 'test-language';
const client = new TestLanguage();
// If you have access to Node `fs` we recommend using `fs.createReadStream()`:
await client.api.v2.segments.imports.create('segmentKey', {
projectKey: 'projectKey',
environmentKey: 'environmentKey',
file: fs.createReadStream('/path/to/file'),
});
// Or if you have the web `File` API you can pass a `File` instance:
await client.api.v2.segments.imports.create('segmentKey', {
projectKey: 'projectKey',
environmentKey: 'environmentKey',
file: new File(['my bytes'], 'file'),
});
// You can also pass a `fetch` `Response`:
await client.api.v2.segments.imports.create('segmentKey', {
projectKey: 'projectKey',
environmentKey: 'environmentKey',
file: await fetch('https://somesite/file'),
});
// Finally, if none of the above are convenient, you can use our `toFile` helper:
await client.api.v2.segments.imports.create('segmentKey', {
projectKey: 'projectKey',
environmentKey: 'environmentKey',
file: await toFile(Buffer.from('my bytes'), 'file'),
});
await client.api.v2.segments.imports.create('segmentKey', {
projectKey: 'projectKey',
environmentKey: 'environmentKey',
file: await toFile(new Uint8Array([0, 1, 2]), 'file'),
});处理错误
当库不能连接到API时, 或者如果API返回非成功状态码(即4xx或5xx响应), 的一个子类 APIError 将被抛出:
async function main() {
const v2s = await client.api.v2.list().catch(async (err) => {
if (err instanceof TestLanguage.APIError) {
console.log(err.status); // 400
console.log(err.name); // BadRequestError
console.log(err.headers); // {server: 'nginx', ...}
} else {
throw err;
}
});
}
main();错误代码如下:
| 状态代码 | 错误类型 |
|---|---|
| 400 | BadRequestError |
| 401 | AuthenticationError |
| 403 | PermissionDeniedError |
| 404 | NotFoundError |
| 422 | UnprocessableEntityError |
| 429 | RateLimitError |
| >=500 | InternalServerError |
| 无 | APIConnectionError |
重试
默认情况下,某些错误将自动重试2次,并具有短暂的指数回退。 连接错误(例如,由于网络连接问题),408请求超时,409冲突, 默认情况下,429速率限制和>=500内部错误都将重试。
您可以使用 maxRetries 配置或禁用此选项:
// Configure the default for all requests:
const client = new TestLanguage({
maxRetries: 0, // default is 2
});
// Or, configure per-request:
await client.api.v2.list({
maxRetries: 5,
});超时
默认情况下,请求在1分钟后超时。您可以使用 timeout 选项:
// Configure the default for all requests:
const client = new TestLanguage({
timeout: 20 * 1000, // 20 seconds (default is 1 minute)
});
// Override per-request:
await client.api.v2.list({
timeout: 5 * 1000,
});在超时时 APIConnectionTimeoutError 被抛出。
请注意,请求的超时时间为 默认情况下重试两次.
高级用法
访问原始响应数据(例如,标头)
“生” Response 返回由 fetch() 可以通过以下方式访问 .asResponse() 方法论 APIPromise 键入所有方法都返回的值。 此方法在收到成功响应的标头后立即返回,并且不消耗响应正文,因此您可以自由编写自定义解析或流式逻辑。
您还可以使用 .withResponse() 获取原始数据的方法 Response 以及解析的数据。 不像 .asResponse() 此方法消耗正文,解析后返回。
const client = new TestLanguage();
const response = await client.api.v2.list().asResponse();
console.log(response.headers.get('X-My-Header'));
console.log(response.statusText); // access the underlying Response object
const { data: v2s, response: raw } = await client.api.v2.list().withResponse();
console.log(raw.headers.get('X-My-Header'));
console.log(v2s.links);日志记录
\[!重要\] 所有日志消息仅用于调试。日志消息的格式和内容 可能会在发布之间发生变化。
日志级别
日志级别可以通过两种方式配置:
- 通过
TEST_LANGUAGE_LOG环境变量 - 使用
logLevel客户端选项(如果设置,则覆盖环境变量)
import TestLanguage from 'test-language';
const client = new TestLanguage({
logLevel: 'debug', // Show all log messages
});可用日志级别,从最详细到最不详细:
'debug'-显示调试消息、信息、警告和错误'info'-显示信息消息、警告和错误'warn'-显示警告和错误(默认)'error'-仅显示错误'off'-禁用所有日志记录
在 'debug' 级别,记录所有HTTP请求和响应,包括标头和正文。 一些与身份验证相关的标头被编辑,但请求和响应正文中的敏感数据 可能仍然可见。
自定义记录器
默认情况下,此库登录到 globalThis.console。您还可以提供自定义记录器。
在提供自定义记录器时 logLevel 选项仍然控制发出哪些消息,消息 低于配置级别的数据将不会发送到您的记录器。
import TestLanguage from 'test-language';
import pino from 'pino';
const logger = pino();
const client = new TestLanguage({
logger: logger.child({ name: 'TestLanguage' }),
logLevel: 'debug', // Send all messages to pino, allowing it to filter
});提出定制/未记录的请求
键入此库是为了方便访问文档化的API。如果你需要访问无证件 端点、参数或响应属性,库仍然可以使用。
未记录的端点
要向未记录的端点发出请求,您可以使用 client.get, client.post,以及其他HTTP动词。 在发出这些请求时,客户端上的选项(如重试)将得到尊重。
await client.post('/some/path', {
body: { some_prop: 'foo' },
query: { some_query_arg: 'bar' },
});未记录的请求参数
要使用未记录的参数发出请求,您可以使用 // @ts-expect-error 关于无证 参数。此库不会在运行时验证请求是否与类型匹配,因此您可以使用任何额外的值 send将按原样发送。
client.foo.create({
foo: 'my_param',
bar: 12,
// @ts-expect-error baz is not yet public
baz: 'undocumented option',
});对于与 GET 动词,任何额外的参数都将在查询中,所有其他请求都将发送 正文中的额外参数。
如果你想显式地发送一个额外的参数,你可以用 query, body,以及 headers 请求 选项。
未记录的响应属性
要访问未记录的响应属性,您可以使用以下命令访问响应对象 // @ts-expect-error 在…上 或者将响应对象转换为所需类型。与请求参数一样,我们不 从API的响应中验证或删除额外的属性。
自定义获取客户端
默认情况下,此库需要一个全局 fetch 功能已定义。
如果你想使用不同的 fetch 函数,您可以对全局进行polyfill:
import fetch from 'my-fetch';
globalThis.fetch = fetch;或者将其传递给客户:
import TestLanguage from 'test-language';
import fetch from 'my-fetch';
const client = new TestLanguage({ fetch });获取选项
如果你想设置自定义 fetch 选项而不覆盖 fetch 功能,您可以提供 fetchOptions 对象在实例化客户端或发出请求时。(请求特定选项会覆盖客户端选项。)
import TestLanguage from 'test-language';
const client = new TestLanguage({
fetchOptions: {
// `RequestInit` options
},
});配置代理
要修改代理行为,您可以提供自定义 fetchOptions 添加特定于运行时的代理 请求选项:
节点 \[文档\]
import TestLanguage from 'test-language';
import * as undici from 'undici';
const proxyAgent = new undici.ProxyAgent('http://localhost:8888');
const client = new TestLanguage({
fetchOptions: {
dispatcher: proxyAgent,
},
});包子 \[文档\]
import TestLanguage from 'test-language';
const client = new TestLanguage({
fetchOptions: {
proxy: 'http://localhost:8888',
},
});德诺 \[文档\]
import TestLanguage from 'npm:test-language';
const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });
const client = new TestLanguage({
fetchOptions: {
client: httpClient,
},
});常见问题
语义版本控制
此套餐通常遵循 学期 尽管某些向后不兼容的更改可能会作为次要版本发布:
- 仅影响静态类型而不破坏运行时行为的更改。
- 对库内部的更改,这些更改在技术上是公开的,但不是为外部使用而设计或记录的。 _(请在GitHub上发布一个问题,让我们知道您是否依赖这些内部机制。)_
- 我们预计在实践中不会影响绝大多数用户的变化。
我们认真对待向后兼容性,并努力确保您能够获得平稳的升级体验。
我们非常期待您的反馈;请打开一个 问题 有问题、错误或建议。
需求
支持TypeScript>=4.9。
支持以下运行时:
- Web浏览器(最新的Chrome、Firefox、Safari、Edge等)
- Node.js 20 LTS或更高版本(非 EOL)版本。
- Deno v1.28.0或更高版本。
- Bun 1.0或更高版本。
- Cloudflare员工。
- Vercel Edge运行时。
- Jest 28或更大
"node"环境("jsdom"目前不支持)。 - Nitro v2.6或更高版本。
请注意,目前不支持React Native。
如果您对其他运行时环境感兴趣,请在GitHub上打开或投票一个问题。
贡献
看 贡献文档.
