@gravity-ui/sdk ! (简体中文)

SDK 与 REST/GRPC API 合作实施
安装
npm install --save-dev @gravity-ui/sdk
使用量
您需要导入 sdkFactory 财务报告和审定财务报表 Schema,并创建一个类的例子.
如果计划不分为范围:
import sdkFactory from '@gravity-ui/sdk';
import type Schema from '<schemas package>';
const config = {
csrfToken: 'secret-token',
endpoint: '/gateway',
};
const sdk = sdkFactory<{root: typeof Schema}>(config);
如果计划被分成了范围:
import sdkFactory from '@gravity-ui/sdk';
import type Schema from '<schemas package>';
import type LocalSchema from '../../shared/schemas';
const config = {
csrfToken: 'secret-token',
endpoint: '/gateway',
};
const sdk = sdkFactory<{root: typeof Schema; local: typeof LocalSchema}>(config);
结构 config数字 :
import {AxiosRequestConfig} from 'axios';
interface SdkConfig {
// Custom Axios settings
axiosConfig?: AxiosRequestConfig;
// CSRF-token
csrfToken?: string;
// The endpoint to which the request from the client will be sent. By default, "/api" is used
endpoint?: string;
// Custom error handler. If the configuration is not specified, the default one is used
handleRequestError?: (error: unknown) => any;
}
在代码中,SDK方法的引用看起来是这样:
sdk.<scope>.<service>.<action>(data, options); // => returns a CancelablePromise
如果默认终点值 /api 指定,完整的请求路径将像这样 :
/api/:scope/:service/:action
有一个特殊的范围叫 root其方法在不明确规定范围的情况下可以使用.
以下电话等同:
sdk.root.<service>.<action>(data, options);
sdk.<service>.<action>(data, options);
但完整的请求路径总是包括范围:
/api/root/:service/:action
结构 options数字 :
interface SdkOptions {
// Request identifier. The previous request with the same identifier will be canceled
concurrentId?: string;
// Ability to specify a specific number of retries for certain endpoints. By default, the number of retries is 0
retries?: number;
// Ability to specify a specific timeout for certain endpoints.
// By default, the configuration is taken from axiosConfig or set to 60 seconds
timeout?: number;
// Ability to specify specific headers when making a call
headers?: Record<string, unknown>;
// Abort the request, including a response stream that is being read
signal?: AbortSignal;
}
简化答复
与 stream: true 请求通过轴取适配器,承诺与反应机构作为一个 ReadableStream<Uint8Array> 头头一到 网关行动必须源源不断地作出反应,例如,REST行动必须与 responseType: 'stream'。 。 。 .
const stream = await sdk.<scope>.<service>.<action>(data, {stream: true, signal});
const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
console.log(chunk.value);
}
超时一直运行到流结束, 所以流请求没有超时, 除非 timeout 通过。 一旦反应信头到达, cancel() 财务报告和审定财务报表 concurrentId 不再影响请求 : signal 或者说 reader.cancel()。从正文读出网关错误,并照常予以拒绝 signal 中止读取出错的正文.
援引外部方法
通过 sdk,您有能力调用外部方法,这些方法在计划中没有定义。 这样的电话看起来是这样的:
sdk(config, options);
论点 config 有类型 AxiosRequestConfig,参数选项有类型 SdkOptions 说明.
可撤销的承诺
为了创造可以取消的承诺,套件输出一个叫做 CancellablePromise(promise: Promise, cancel: () => void)。 。 。 .
其他方法
sdk.setLang () (中文(简体) )
允许设置用户语言, 语言将通过特殊方式传递到所有引用的端点 accept-language 头曰.
sdk.set 默认页眉 ()
允许设置将传递到所有引用的端点的基头 .