Minikai TypeScript库
Minikai TypeScript库提供了从TypeScript访问Minikai api的便利。
目录表
安装
npm i -s minikai
参考
这个库的完整参考资料是可用的 在这里。
用法
实例化和使用客户端如下:
import { MinikaiClient } from "minikai";
const client = new MinikaiClient({ token: "YOUR_TOKEN" });
await client.labelGroups.createLabelGroup({
name: "name",
resourceType: "record"
});
环境
这个SDK允许您为API请求配置不同的环境。
import { MinikaiClient, MinikaiEnvironment } from "minikai";
const client = new MinikaiClient({
environment: MinikaiEnvironment.Australia,
});
请求和响应类型
SDK将所有的请求和响应类型导出为TypeScript接口。简单地导入它们 名称空间:
import { Minikai } from "minikai";
const request: Minikai.CreateLabelGroupCommand = {
...
};
异常处理
当API返回非成功状态码(4xx或5xx响应)时,将生成以下错误的子类 会被扔。
import { MinikaiError } from "minikai";
try {
await client.labelGroups.createLabelGroup(...);
} catch (err) {
if (err instanceof MinikaiError) {
console.log(err.statusCode);
console.log(err.message);
console.log(err.body);
console.log(err.rawResponse);
}
}
文件上传
您可以使用客户端上传文件:
import { createReadStream } from "fs";
import * as fs from "fs";
import { MinikaiClient } from "minikai";
const client = new MinikaiClient({ token: "YOUR_TOKEN" });
await client.minis.uploadMiniProfilePicture("id", {
file: fs.createReadStream("/path/to/your/file")
});
客户端接受各种类型的文件上传参数:
- 流类型:
fs.ReadStream,stream.Readable,ReadableStream - 缓冲类型:
Buffer,Blob,File,ArrayBuffer,ArrayBufferView,Uint8Array
元数据
您可以在上传文件时配置元数据:
const file: Uploadable.WithMetadata = {
data: createReadStream("path/to/file"),
filename: "my-file", // optional
contentType: "audio/mpeg", // optional
contentLength: 1949, // optional
};
或者,您可以直接从文件路径上传文件:
const file : Uploadable.FromPath = {
path: "path/to/file",
filename: "my-file", // optional
contentType: "audio/mpeg", // optional
contentLength: 1949, // optional
};
元数据用于设置 Content-Length, Content-Type, Content-Disposition 头。如果没有提供,客户端将尝试自动确定它们。
例如, fs.ReadStream 有一个 path 属性,SDK使用该属性从文件系统检索文件大小,而不将其加载到内存中。
二进制响应
方法从端点使用二进制数据 BinaryResponse 类型,它允许您选择如何使用数据:
const response = await client.minis.downloadMiniProfilePicture(...);
const stream: ReadableStream<Uint8Array> = response.stream();
// const arrayBuffer: ArrayBuffer = await response.arrayBuffer();
// const blob: Blob = response.blob();
// const bytes: Uint8Array = response.bytes();
// You can only use the response body once, so you must choose one of the above methods.
// If you want to check if the response body has been used, you can use the following property.
const bodyUsed = response.bodyUsed;
将二进制响应保存到文件中
node . js
ReadableStream(最有效)
import { createWriteStream } from 'fs'; import { Readable } from 'stream'; import { pipeline } from 'stream/promises'; const response = await client.minis.downloadMiniProfilePicture(...); const stream = response.stream(); const nodeStream = Readable.fromWeb(stream); const writeStream = createWriteStream('path/to/file'); await pipeline(nodeStream, writeStream);ArrayBuffer
import { writeFile } from 'fs/promises'; const response = await client.minis.downloadMiniProfilePicture(...); const arrayBuffer = await response.arrayBuffer(); await writeFile('path/to/file', Buffer.from(arrayBuffer));团
import { writeFile } from 'fs/promises'; const response = await client.minis.downloadMiniProfilePicture(...); const blob = await response.blob(); const arrayBuffer = await blob.arrayBuffer(); await writeFile('output.bin', Buffer.from(arrayBuffer));字节(UIntArray8)
import { writeFile } from 'fs/promises'; const response = await client.minis.downloadMiniProfilePicture(...); const bytes = await response.bytes(); await writeFile('path/to/file', bytes);
包子
ReadableStream(最有效)
const response = await client.minis.downloadMiniProfilePicture(...); const stream = response.stream(); await Bun.write('path/to/file', stream);ArrayBuffer
const response = await client.minis.downloadMiniProfilePicture(...); const arrayBuffer = await response.arrayBuffer(); await Bun.write('path/to/file', arrayBuffer);团
const response = await client.minis.downloadMiniProfilePicture(...); const blob = await response.blob(); await Bun.write('path/to/file', blob);字节(UIntArray8)
const response = await client.minis.downloadMiniProfilePicture(...); const bytes = await response.bytes(); await Bun.write('path/to/file', bytes);
Deno
ReadableStream(最有效)
const response = await client.minis.downloadMiniProfilePicture(...); const stream = response.stream(); const file = await Deno.open('path/to/file', { write: true, create: true }); await stream.pipeTo(file.writable);ArrayBuffer
const response = await client.minis.downloadMiniProfilePicture(...); const arrayBuffer = await response.arrayBuffer(); await Deno.writeFile('path/to/file', new Uint8Array(arrayBuffer));团
const response = await client.minis.downloadMiniProfilePicture(...); const blob = await response.blob(); const arrayBuffer = await blob.arrayBuffer(); await Deno.writeFile('path/to/file', new Uint8Array(arrayBuffer));字节(UIntArray8)
const response = await client.minis.downloadMiniProfilePicture(...); const bytes = await response.bytes(); await Deno.writeFile('path/to/file', bytes);
浏览器
Blob(最有效)
const response = await client.minis.downloadMiniProfilePicture(...); const blob = await response.blob(); const url = URL.createObjectURL(blob); // trigger download const a = document.createElement('a'); a.href = url; a.download = 'filename'; a.click(); URL.revokeObjectURL(url);ReadableStream
const response = await client.minis.downloadMiniProfilePicture(...); const stream = response.stream(); const reader = stream.getReader(); const chunks = []; while (true) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); } const blob = new Blob(chunks); const url = URL.createObjectURL(blob); // trigger download const a = document.createElement('a'); a.href = url; a.download = 'filename'; a.click(); URL.revokeObjectURL(url);ArrayBuffer
const response = await client.minis.downloadMiniProfilePicture(...); const arrayBuffer = await response.arrayBuffer(); const blob = new Blob([arrayBuffer]); const url = URL.createObjectURL(blob); // trigger download const a = document.createElement('a'); a.href = url; a.download = 'filename'; a.click(); URL.revokeObjectURL(url);字节(UIntArray8)
const response = await client.minis.downloadMiniProfilePicture(...); const bytes = await response.bytes(); const blob = new Blob([bytes]); const url = URL.createObjectURL(blob); // trigger download const a = document.createElement('a'); a.href = url; a.download = 'filename'; a.click(); URL.revokeObjectURL(url);
将二进制响应转换为文本
ReadableStream
const response = await client.minis.downloadMiniProfilePicture(...); const stream = response.stream(); const text = await new Response(stream).text();
ArrayBuffer
const response = await client.minis.downloadMiniProfilePicture(...); const arrayBuffer = await response.arrayBuffer(); const text = new TextDecoder().decode(arrayBuffer);
团
const response = await client.minis.downloadMiniProfilePicture(...); const blob = await response.blob(); const text = await blob.text();
字节(UIntArray8)
const response = await client.minis.downloadMiniProfilePicture(...); const bytes = await response.bytes(); const text = new TextDecoder().decode(bytes);
先进的
分包出口
这个SDK支持直接导入子包客户端,这允许JavaScript打包器进行树摇,只包含导入的子包代码。这将导致更小的包大小。
import { LabelGroupsClient } from 'minikai/labelGroups';
const client = new LabelGroupsClient({...});
附加报头
如果您希望发送额外的标头作为请求的一部分,请使用 headers 请求的选项。
import { MinikaiClient } from "minikai";
const client = new MinikaiClient({
...
headers: {
'X-Custom-Header': 'custom value'
}
});
const response = await client.labelGroups.createLabelGroup(..., {
headers: {
'X-Custom-Header': 'custom value'
}
});
其他查询字符串参数
如果希望将其他查询字符串参数作为请求的一部分发送,请使用 queryParams 请求的选项。
const response = await client.labelGroups.createLabelGroup(..., {
queryParams: {
'customQueryParamKey': 'custom query param value'
}
});
重试
SDK配备了自动重试和指数回退。请求将被重试 由于该请求被认为是可重试的,并且重试尝试的次数没有超过配置 重试限制(默认为2)。
重试哪些状态码取决于 retryStatusCodes 发电机配置:
legacy (当前默认值):重试
recommendedretries on
使用 maxRetries 请求选项来配置此行为。
const response = await client.labelGroups.createLabelGroup(..., {
maxRetries: 0 // override maxRetries at the request level
});
超时
SDK默认为60秒超时。使用 timeoutInSeconds 选项配置此行为。
const response = await client.labelGroups.createLabelGroup(..., {
timeoutInSeconds: 30 // override timeout to 30s
});
流产的请求
SDK允许用户在任何时候通过传入一个中止信号来中止请求。
const controller = new AbortController();
const response = await client.labelGroups.createLabelGroup(..., {
abortSignal: controller.signal
});
controller.abort(); // aborts the request
访问原始响应数据
方法提供对原始响应数据(包括标头)的访问 .withRawResponse() 方法。
这个 .withRawResponse() 方法返回一个promise,该promise的结果是一个带有 data 和一个 rawResponse 财产。
const { data, rawResponse } = await client.labelGroups.createLabelGroup(...).withRawResponse();
console.log(data);
console.log(rawResponse.headers['X-My-Header']);
日志记录
SDK支持日志记录。可以通过传入参数来配置日志记录器 logging 对象到客户端选项。
import { MinikaiClient, logging } from "minikai";
const client = new MinikaiClient({
...
logging: {
level: logging.LogLevel.Debug, // defaults to logging.LogLevel.Info
logger: new logging.ConsoleLogger(), // defaults to ConsoleLogger
silent: false, // defaults to true, set to false to enable logging
}
});
这个 logging 对象可以具有以下属性:
level:要使用的日志级别。默认为logging.LogLevel.Info。logger:要使用的记录器。默认为a。logging.ConsoleLogger。silent:是否关闭日志记录器。默认为true。
这个 level 属性可以是以下值之一:
logging.LogLevel.Debuglogging.LogLevel.Infologging.LogLevel.Warnlogging.LogLevel.Error
要提供自定义日志记录器,可以传入一个对象,该对象实现 logging.ILogger 接口。
自定义日志程序示例
下面是一个使用popular的例子 winston 日志库。
import winston from 'winston';
const winstonLogger = winston.createLogger({...});
const logger: logging.ILogger = {
debug: (msg, ...args) => winstonLogger.debug(msg, ...args),
info: (msg, ...args) => winstonLogger.info(msg, ...args),
warn: (msg, ...args) => winstonLogger.warn(msg, ...args),
error: (msg, ...args) => winstonLogger.error(msg, ...args),
};
下面是一个使用popular的例子 pino 日志库。
import pino from 'pino';
const pinoLogger = pino({...});
const logger: logging.ILogger = {
debug: (msg, ...args) => pinoLogger.debug(args, msg),
info: (msg, ...args) => pinoLogger.info(args, msg),
warn: (msg, ...args) => pinoLogger.warn(args, msg),
error: (msg, ...args) => pinoLogger.error(args, msg),
};
自定义获取
SDK提供了一个底层 fetch 方法,用于在静止时发出自定义HTTP请求
受益于sdk级别的配置,如身份验证、重试、超时和日志记录。
这对于调用SDK中尚未支持的API端点非常有用。
const response = await client.fetch("/v1/custom/endpoint", {
method: "GET",
}, {
timeoutInSeconds: 30,
maxRetries: 3,
headers: {
"X-Custom-Header": "custom-value",
},
});
const data = await response.json();
运行时的兼容性
SDK工作在以下运行时:
- node . js 18 +
- Vercel
- Cloudflare工人
- Deno v1.25 +
- 面包1.0 +
- 反应本地
贡献
虽然我们重视对这个SDK的开源贡献,但这个库是通过编程生成的。 直接添加到这个库的内容必须移动到我们的生成代码中, 否则,它们将在下一个生成的版本中被覆盖。请随意打开PR帐户 一个概念的证明,但知道我们将无法合并它。我们建议 一个问题先和我们讨论!
另一方面,对README的贡献总是非常受欢迎的!