@compassdigital/sdk.typescript
编译数字实验室类型SDK
安装
$ npm install --save @compassdigital/sdk.typescript@latest
服务器使用示例
import Provider from "@compassdigital/provider";
import { GetTaskRequest, GetTaskResponse } from "@compassdigital/sdk.typescript/interface/task";
const provider = new Provider({ type: "task" });
provider.on<GetTaskRequest, GetTaskResponse>("get_task", function (req, next): void {
// ...
})
客户端使用示例
证明客户端 :
import { ServiceClient } from "@compassdigital/sdk.typescript";
const api = new ServiceClient({ stage: "dev" });
基本请求 :
const task = await api.get_task(id);
请求选项 :
这些选择可转交任何请求.
interface RequestOptions {
// environment to make requests to
stage?: string;
// authentication token
token?: string;
// additional headers
headers?: Record<string, string>;
// log all requests and responses
debug?: boolean;
// the number of times to retry a request
retry?: number;
// timeout in milliseconds
timeout?: number;
// make requests against this base url.
// per-service base urls are configured as an object
// eg. { order: 'http://localhost:3000', shoppingcart: 'http://localhost:4000' }
// note: the stage property is ignored if base_url is set
base_url?: string;
// intercept outgoing http requests
intercept?: InterceptFn;
}
- 这个
RequestOptions可提供给ServiceClient建筑师或应请求呼叫现场. - 呼叫站点提供的选项将超越转给建筑商的选项.
const api = new ServiceClient({
token: "<token>",
retry: 2,
})
const location = await api.get_location(id, {
token: "<token>",
retry: 2,
})
以下环境变量可用于设定调试目的的默认选项:
P2_SDK_STAGEP2_SDK_TOKENP2_SDK_DEBUGP2_SDK_BASE_URL- 可以通过一个url来拦截所有请求
- 参见http://localhost:3:00
- 可以通过一个逗号分隔列表来配置每个服务的基数 urls
- http://localhost:3:00,购物车=http://localhost:4:00
处理错误 :
非200份答复被否决 ServiceError。 。 。 .
try {
const shoppingcart = await api.get_shoppingcart(id);
} catch (err) {
// Since the error type is `unknown` we must type assert before
// accessing the properties.
if (err instanceof ServiceError) {
console.log(err.status, err.code, err.message);
}
// There are helpers for accessing the status and code
if (ServiceError.code(err) === 400.31) {
console.log("Failed to get menu");
}
}
有一个 ignore 忽略特定状态和错误代码的方便方法 .
const issue: OrderIssue = { items: [] };
await api.post_order_issue(id, issue).ignore(400.18, 400.21);
有一个 combine 返回含有响应或错误的对象的方便方法.
const res = await api.get_task(id).combine();
if (res.ok) {
console.log("task", res.data);
} else {
console.log("error", res.err);
}
测试 :
您可以注册 intercept 函数将重排所有请求.
import {
ServiceClient,
RequestData,
ResponseData,
FetchFn,
} from "@compassdigital/sdk.typescript";
async function intercept(req: RequestData, fetch: FetchFn): Promise<ResponseData> {
expect(req.name).toBe("get_shoppingcart");
return { ok: true, status: 200, body: JSON.stringify({}) }
}
const api = new ServiceClient({ intercept });
代码 Gen
- 添加新服务到
manifest.json。 。 。 . - 运行
npm run gen。 。 。 .