工作记录—servicestack/client的集成

需求

新增的AutoQuery api不再原生手写http请求,而是使用 @servicestack/client请求库。
利用后台生成的文件,里面封装好了请求接口

第一步

在package.json 中添加 “@servicestack/client”: “x.x.xx”,通过npm i 命令安装

第二步

在provider中,添加dtos.ts文件(此文件中包含用于网络请求的函数,如在pos中用到的NoteQuery),并在Module中注入

第三步

在需要进行http请求的provider中,按需引入@servicestack/client,引入生成的dtos文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

// 引入第三方库
import { JsonServiceClient } from '@servicestack/client';
// import dtos provider
import { NoteQuery, QueryResponse } from '../../autoquery.dtos';

// 第一个参数为请求地址, 第二个参数为uri
const client = new JsonServiceClient(ip_address + '/sapi');

// 该库默认配置为 "includes"(携带cookie),若不需要则更改配置为"omit"
client.credentials = 'omit';
let request = new NoteQuery();

// get() 的第二个参数可传入filter
let response = await client.get(request, { type: note_type });
if (response && response.results)
{
// process data
}

第四步

在tsconfig中配置该文件的转译,否则浏览器不能识别
"*.dtos.ts"

如何生成dtos文件

  • npm install -g @servicestack/cli
  • typescript-ref http://xxx.revopos.io/sapi autoquery (第二个参数用于文件命名,可自定义)

tips 相关文档:
https://www.npmjs.com/package/@servicestack/cli
https://www.npmjs.com/package/@servicestack/client

查看评论