什么是 tsdk
tsdk 是一款 TypeScript 项目开发工具。通过 tsdk,开发人员可以更轻松地在项目间共享代码,以及端到端类型安全的 API 开发,确保类型的一致性,从而减少潜在的错误,提高开发效率。
主要特点
- 类型安全:确保前后端通信以及不同模块之间的类型一致性
- 代码共享:简化在项目不同部分之间共享代码的流程
- 代码生成:生成直接调用接口的代码,以及支持 SWR 和 ReactQuery 钩子生成
- 更多:基于生成的 fe-sdk/permissions.json 可以生成自己想要的模版代码,比如检测登录,导入接口权限等
动机:为什么 tsdk
我们从传统的 API 开发流程来说:
- 后端写好接口和接口文档
- 前端根据接口文档再封装请求接口的代码。
tsdk 可以帮助我们省去第二步,如何做到?我们从一个最简单的 Hello World
例子开始。
一个简单的原始后端接口
这里拿 expressjs.com (opens in a new tab) 中的 Hello World (opens in a new tab) 例子来说明什么是 端到端类型安全 API
,以及 tsdk 的基本工作原理。
一个原始的简单接口:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
请求接口代码编写
根据后端代码,HTTP 请求 get
/
返回的结果是字符串,编写如下代码:
function HelloWorld(): Promise<string> {
return fetch('/').then((res) => res.text());
}
如果可以跳过 请求接口代码
的编写,只需要这样调用:
import { HelloWorld } from 'fe-sdk';
HelloWorld().then((res) => {
console.log(res);
});
在这里我们知道 res 是 string 类型。而且不需要手动编写,想使用,直接引用即可,这就是我们所说的端到端类型安全开发。
端到端类型安全实现
要做到端到端类型安全,需要我们重新组织接口的代码。
首先抽出接口配置到 HelloWorld.apiconf.ts
:
export const HelloWorldConfig = {
path: '/',
method: 'get',
};
export type HelloWorldReq = any;
export type HelloWorldRes = string;
根据配置改变原来的接口写法(保持一致性):
import express from 'express';
import { HelloWorldConfig, HelloWorldReq, HelloWorldRes } from './HelloWorld.apiconf';
const app = express();
const port = 3000;
app[HelloWorldConfig.method](HelloWorldConfig.path, (req, res) => {
const result: HelloWorldRes = 'Hello World!';
res.send(result);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
生成调用代码
既然已经知道了接口请求方法,请求路径,请求参数类型,响应类型,那么我们可以生成如下面的请求接口代码:
import { HelloWorldConfig, HelloWorldReq, HelloWorldRes } from './HelloWorld.apiconf';
export function HelloWorld(req: HelloWorldReq): Promise<HelloWorldRes> {
return fetch(HelloWorldConfig.path, { method: HelloWorldConfig.method }).then((res) =>
res.text()
);
}
总结
tsdk 的运作原理不是非常复杂。
下一步,我们使用 tsdk 写一个可以运行的完整版 hello world
例子,快速开始。