@ deliverart/ sdk- js- 分数
交付艺术JavaScript SDK的核心包. 提供API客户端,插件系统,以及基础请求/响应处理.
安装
npm install @deliverart/sdk-js-core
# or
pnpm add @deliverart/sdk-js-core
# or
yarn add @deliverart/sdk-js-core
导出类型
图像
type ApiClient<Extensions extends ApiExtension = NonNullable<unknown>>
主要API客户端接口提供了制作API调用和管理插件的方法.
方法:
call<TInputSchema, TOutputSchema, Q, H>(request: AbstractApiRequest): Promise<output<TOutputSchema>>- 执行API请求addPlugin<T extends ApiExtension>(plugin: ApiClientPlugin<T>): ApiClient<T>- 添加插件以扩展客户端功能addRequestMiddleware(middleware: RequestMiddleware): void- 添加中间软件拦截请求addResponseMiddleware(middleware: ResponseMiddleware): void- 添加中间软件以拦截响应
抽象请求
abstract class AbstractApiRequest<
TInputSchema extends ZodType<any, any, any>,
TOutputSchema extends ZodType<any, any, any>,
Query = unknown,
Headers = unknown
>
所有 API 请求的基础类 。 扩展此类以创建自定义 API 请求 .
摘要属性 :
method: 'GET' | 'POST' | 'PATCH' | 'DELETE'- HTTP方法(所需)contentType: 'application/json' | 'multipart/form-data' | 'application/merge-patch+json'- 内容-类型标题(需要)accept: 'application/json'- 接受信头(需要)inputSchema: TInputSchema- 请求审定的Zod计划(需要)outputSchema: TOutputSchema- Zod schema用于响应验证(需要)querySchema?: ZodType<Query>- 用于查询参数的Zod计划(可选)headersSchema?: ZodType<Headers>- 标头的Zod schema(可选)
摘要方法:
getPath(): string- 返回 API 端点路径( 需要)
内设方法:
validateInput(): output<TInputSchema>- 验证请求输入validateQuery(): Query | undefined- 验证查询参数validateHeaders(): Headers | undefined- 验证信头validateOutput(data: unknown): output<TOutputSchema>- 验证答复parseResponse(data: unknown, rawResponse?: Response): output<TOutputSchema>- 分析并验证反应(可以推翻)
扩展
type ApiExtension = Record<string, unknown>
添加新方法到 API 客户端的插件扩展的基础类型 .
ApiClient 缓冲
interface ApiClientPlugin<T extends ApiExtension = Record<string, unknown>> {
setup: (client: ApiClient<Record<string, unknown>>) => T
}
用于创建扩展API客户端功能的插件的接口.
错误
输入参数错误
class InputValidationError extends Error {
constructor(public readonly issues: ZodIssue[])
}
当请求输入验证失败时抛出 .
属性 :
issues: ZodIssue[]- Zod的验证错误矩阵
输出校正误差
class OutputValidationError extends Error {
constructor(public readonly issues: ZodIssue[])
}
当响应验证失败时抛出 .
属性 :
issues: ZodIssue[]- Zod的验证错误矩阵
使用量
创建 API 客户端
import { createApiClient } from '@deliverart/sdk-js-core';
const client = createApiClient({
baseUrl: 'https://api.deliverart.com'
});
参数:
baseUrl: string(需要) - 所有 API 请求的基础 URL
创建自定义请求
import { AbstractApiRequest } from '@deliverart/sdk-js-core';
import { z } from 'zod';
// Define input schema
const createUserInputSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.coerce.number().min(18).optional()
});
// Define output schema
const userResponseSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string(),
age: z.coerce.number().nullable(),
createdAt: z.string()
});
// Define query parameters schema (optional)
const getUsersQuerySchema = z.object({
page: z.coerce.number().optional(),
limit: z.coerce.number().optional(),
search: z.string().optional()
});
// Create the request class
class CreateUser extends AbstractApiRequest<
typeof createUserInputSchema,
typeof userResponseSchema
> {
readonly method = 'POST';
readonly contentType = 'application/json';
readonly accept = 'application/json';
readonly inputSchema = createUserInputSchema;
readonly outputSchema = userResponseSchema;
readonly querySchema = undefined;
readonly headersSchema = undefined;
constructor(input: z.input<typeof createUserInputSchema>) {
super(input);
}
getPath(): string {
return '/users';
}
}
// Request with path parameters
class GetUser extends AbstractApiRequest<
typeof z.undefined,
typeof userResponseSchema
> {
readonly method = 'GET';
readonly contentType = 'application/json';
readonly accept = 'application/json';
readonly inputSchema = z.undefined();
readonly outputSchema = userResponseSchema;
readonly querySchema = undefined;
readonly headersSchema = undefined;
private readonly userId: string;
constructor(userId: string) {
super(undefined);
this.userId = userId;
}
getPath(): string {
return `/users/${this.userId}`;
}
}
// Request with query parameters
class GetUsers extends AbstractApiRequest<
typeof z.undefined,
typeof z.array(userResponseSchema),
z.infer<typeof getUsersQuerySchema>
> {
readonly method = 'GET';
readonly contentType = 'application/json';
readonly accept = 'application/json';
readonly inputSchema = z.undefined();
readonly outputSchema = z.array(userResponseSchema);
readonly querySchema = getUsersQuerySchema;
readonly headersSchema = undefined;
constructor(options?: { query?: z.infer<typeof getUsersQuerySchema> }) {
super(undefined, options);
}
getPath(): string {
return '/users';
}
}
制作API电话
import { client } from './client';
// Create a user
const newUser = await client.call(new CreateUser({
name: 'John Doe',
email: '[email protected]',
age: 25
}));
// Get a user
const user = await client.call(new GetUser('user-123'));
// Get users with filters
const users = await client.call(new GetUsers({
query: {
page: 1,
limit: 10,
search: 'john'
}
}));
正在添加中间软件
请求中间软件
client.addRequestMiddleware(async (ctx) => {
console.log('Making request to:', ctx.url.toString());
// Modify headers
return {
...ctx,
init: {
...ctx.init,
headers: {
...ctx.init.headers,
'X-Custom-Header': 'value'
}
}
};
});
参数:
ctx.url: URL- 请求 URLctx.init: RequestInit- 获取选项
返回 : 已修改 RequestContext 或原上下文
中间响应软件
client.addResponseMiddleware(async (parsed, requestCtx) => {
console.log('Response status:', parsed.response.status);
console.log('Response body:', parsed.body);
return parsed;
});
参数:
parsed.response: Response- 获取响应对象parsed.body: unknown- 解析的反应机构requestCtx: RequestContext- 最初请求的背景
返回 : 已修改 ParsedResponse 或原始解析的答复
创建插件
import { ApiClient, ApiClientPlugin, ApiExtension } from '@deliverart/sdk-js-core';
// Define the extension interface
interface LoggerExtension extends ApiExtension {
logger: {
enable: () => void;
disable: () => void;
};
}
// Create the plugin
class LoggerPlugin implements ApiClientPlugin<LoggerExtension> {
private enabled = true;
setup(client: ApiClient): LoggerExtension {
// Add request middleware
client.addRequestMiddleware(async (ctx) => {
if (this.enabled) {
console.log('[Request]', ctx.init.method, ctx.url.toString());
}
return ctx;
});
// Add response middleware
client.addResponseMiddleware(async (parsed, ctx) => {
if (this.enabled) {
console.log('[Response]', parsed.response.status);
}
return parsed;
});
// Return extension methods
return {
logger: {
enable: () => {
this.enabled = true;
},
disable: () => {
this.enabled = false;
}
}
};
}
}
// Use the plugin
const client = createApiClient({ baseUrl: 'https://api.example.com' })
.addPlugin(new LoggerPlugin());
// Now you can use the logger methods
client.logger.disable();
client.logger.enable();
处理错误
import { InputValidationError, OutputValidationError } from '@deliverart/sdk-js-core';
try {
await client.call(new CreateUser({
name: '', // Invalid: min length is 1
email: 'invalid-email', // Invalid email format
}));
} catch (error) {
if (error instanceof InputValidationError) {
console.error('Input validation failed:');
error.issues.forEach(issue => {
console.error(`- ${issue.path.join('.')}: ${issue.message}`);
});
} else if (error instanceof OutputValidationError) {
console.error('Response validation failed:');
error.issues.forEach(issue => {
console.error(`- ${issue.path.join('.')}: ${issue.message}`);
});
} else {
console.error('Other error:', error);
}
}
高级特性
自定义响应解析
覆盖 parseResponse 以自定义解析回复:
import { Paginated, responseToPagination } from '@deliverart/sdk-js-global-types';
class GetUsers extends AbstractApiRequest</*...*/> {
// ... other properties ...
parseResponse(data: unknown, rawResponse: Response): Paginated<User> {
const users = z.array(userResponseSchema).parse(data);
return this.validateOutput({
data: users,
pagination: responseToPagination(rawResponse)
});
}
}
格式数据请求
const uploadImageInputSchema = z.instanceof(FormData);
class UploadImage extends AbstractApiRequest<
typeof uploadImageInputSchema,
typeof imageResponseSchema
> {
readonly method = 'POST';
readonly contentType = 'multipart/form-data';
readonly accept = 'application/json';
readonly inputSchema = uploadImageInputSchema;
readonly outputSchema = imageResponseSchema;
constructor(formData: FormData) {
super(formData);
}
getPath(): string {
return '/images';
}
}
// Usage
const formData = new FormData();
formData.append('file', fileBlob);
formData.append('name', 'My Image');
const image = await client.call(new UploadImage(formData));
共享运行时间类型
@deliverart/sdk-js-global-types 是一个运行时间依赖。 核心序列化
返回同样的 IriObject 类; 捆绑私有
复制中断实例检查和消费者使用的名义声明类型.
新建两个软件包后运行 pnpm --filter @deliverart/sdk-js-core test:artifacts
核查无害环境管理和通用JS软件包的边界.
许可证
麻省理工学院