Hono Adapter 适配器使用
Hono 适配器使用分别包扩后端使用和前端使用。
后端使用
import { Hono, HonoRequest } from 'hono';
import { serve } from '@hono/node-server';
import { honoAdapterFactory } from 'tsdk-server-adapters/lib/hono-adapter';
import { checkMethodHasBody, ProtocolTypes } from '@/src/shared/tsdk-helper';
import { RequestInfo, routeBus } from './gen-route';
const port = 3000;
const app = new Hono();
app.get('/', (c) => {
return c.text('hi, from hono.');
});
app.all(
'/api/:type/*',
honoAdapterFactory<RequestInfo>({
routeBus,
async getReqInfo(req: HonoRequest) {
return {
ip: '',
lang: 'zh-CN',
type: (req.param() as { type: string }).type,
token: req.header['authorization'],
};
},
getType(reqInfo) {
return reqInfo.type;
},
async getData(req) {
return checkMethodHasBody(req.method) ? req.raw.body : req.query();
},
})
);
serve({
fetch: app.fetch,
port,
});
console.log(`Hono server running at http://localhost:${port}`);
前端使用 xior(基于 fetch)
xior 基于 fetch, API 类似 axios, https://www.npmjs.com/package/xior (opens in a new tab)
💡
Hono 与 Express 都是 http 协议的 web 框架,所以使用方式一致。
import xior from 'xior';
import { setHandler, setXiorInstance, xiorHandler } from 'fe-sdk';
const xiorInstance = xior.create({ baseURL: `/api/user` });
setXiorInstance(xiorInstance);
setHandler(xiorHandler);
再更新 tsdk.config.js
,添加配置 httpLib: 'xior'
tsdk.config.js
/** @type {import('tsdk').TSDKConfig} */
module.exports = {
...
httpLib: 'xior',
...
}
前端使用 axios
💡
Hono 与 Express 都是 http 协议的 web 框架,所以使用方式一致。
import axios from 'axios';
import { setHandler, setAxiosInstance, axiosHandler } from 'fe-sdk';
const axiosInstance = axios.create({ baseURL: `/api/user` });
setAxiosInstance(axiosInstance);
setHandler(axiosHandler);