Skip to content

Commit

Permalink
feat: support xior(fetch) 😎
Browse files Browse the repository at this point in the history
  • Loading branch information
suhaotian committed Feb 20, 2024
1 parent 443018e commit f91c383
Show file tree
Hide file tree
Showing 30 changed files with 641 additions and 261 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

This is the log of notable changes to the `tsdk` that are developer-facing.

### 0.1.5 2024/2/20

- Feat: add fetch support (use xior, similar axios API: https://www.npmjs.com/package/xior)
- Chore: bump deps
- Chore: update documentation, add `xior` part and fix some typo

### 0.1.4 2024/01/20

- Fix: windows build
Expand Down
2 changes: 1 addition & 1 deletion examples/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import '@total-typescript/ts-reset';
const { manifest } = Constants;
const baseURL =
// process.env.NODE_ENV === 'production'
// ? '' // @todo 使用环境变量打包
// ? ''
// :
(() => {
// TODO - put a "prod" api server somewhere
Expand Down
2 changes: 1 addition & 1 deletion examples/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"react-dom": "18.2.0",
"react-native": "^0.72.3",
"react-native-web": "^0.19.6",
"socket.io-client": "^4.7.2"
"socket.io-client": "^4.7.4"
},
"devDependencies": {
"@configs/vitest-config": "workspace:*",
Expand Down
8 changes: 4 additions & 4 deletions examples/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@
"cors": "^2.8.5",
"express": "^4.18.2",
"reflect-metadata": "^0.1.13",
"socket.io": "^4.7.2",
"socket.io": "^4.7.4",
"typeorm": "^0.3.17",
"kysely": "^0.26.3",
"typeorm-cursor-pagination": "^0.10.1",
"utf-8-validate": "^6.0.3",
"ws": "^8.13.0",
"zod": "^3.22.4",
"hono": "^3.10.2",
"hono": "^4.0.4",
"fastify": "^4.24.3",
"@fastify/express": "^2.3.0",
"@hono/node-server": "^1.2.3",
Expand All @@ -44,10 +44,10 @@
"@configs/test-config": "workspace:*",
"@configs/ts-config": "workspace:*",
"@configs/eslint-config": "workspace:*",
"@nestjs/cli": "^10.2.1",
"@nestjs/cli": "^10.3.2",
"@types/express": "^4.17.17",
"@types/ws": "^8.5.5",
"socket.io-client": "^4.7.2",
"socket.io-client": "^4.7.4",
"tsdk": "workspace:*"
},
"eslintConfig": {
Expand Down
7 changes: 4 additions & 3 deletions examples/server/packages/fe-sdk-demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
},
"dependencies": {
"zod": "^3",
"axios": "1.6.1",
"axios": "^1.6.7",
"xior": "^0.0.3",
"change-case": "^4.1.2",
"kysely": "^0.26.3",
"@tanstack/react-query": "^5.14.0",
"@tanstack/react-query": "^5.22.2",
"i18next": "^23.7.13",
"intl-pluralrules": "^2.0.1"
},
Expand All @@ -22,7 +23,7 @@
"@tsconfig/recommended": "^1.0.3"
},
"peerDependencies": {
"socket.io-client": "^4.7.2"
"socket.io-client": "^4.7.4"
},
"peerDependenciesMeta": {
"socket.io-client": {
Expand Down
5 changes: 3 additions & 2 deletions examples/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
"react": "18.2.0",
"react-dom": "18.2.0",
"react-native-web": "^0.19.6",
"socket.io-client": "^4.7.2",
"axios": "1.6.1"
"socket.io-client": "^4.7.4",
"axios": "^1.6.7",
"xior": "^0.0.3"
},
"devDependencies": {
"@configs/vitest-config": "workspace:*",
Expand Down
2 changes: 1 addition & 1 deletion examples/web/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import styles from '../styles/Home.module.css';

const baseURL =
// process.env.NODE_ENV === 'production'
// ? process.env.BASE_URL // @todo 使用环境变量打包
// ? process.env.BASE_URL
// :
(() => {
if (typeof window === 'undefined') return;
Expand Down
96 changes: 96 additions & 0 deletions examples/web/pages/xior/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import {
setHandler,
setSocketIOInstance,
socketIOHandler,
setXiorInstance,
xiorHandler,
getHandler,
} from 'fe-sdk-demo';
import { QueryTodoRes } from 'fe-sdk-demo/lib/apiconf-refs';
import { TodoStatus } from 'fe-sdk-demo/lib/modules/todo/Todo.entity';
import { AddTodo, QueryTodo } from 'fe-sdk-demo/lib/user-api';
import Head from 'next/head';
import { useState, useEffect } from 'react';
// eslint-disable-next-line import/namespace
import { io as SocketIO } from 'socket.io-client';
import xior from 'xior';

import styles from '../../styles/Home.module.css';

const baseURL =
// process.env.NODE_ENV === 'production'
// ? process.env.BASE_URL
// :
(() => {
if (typeof window === 'undefined') return;
return (
window?.location.protocol + '//' + window?.location.host.split(':')[0] + ':' + 3012 + '/'
);
})();

const apiType = 'user';
const socketURL = baseURL;
const apiURL = baseURL + `api/${apiType}`;

export default function Home() {
const [handlerName, setHanlderName] = useState('');
const [result, setResult] = useState<QueryTodoRes>();

useEffect(() => {
const io = SocketIO(socketURL, {
transports: ['websocket'],
query: {
type: apiType,
},
});
setSocketIOInstance(io);
setHandler(socketIOHandler);

setHanlderName(getHandler().name);

io.on('connect', async () => {
await AddTodo({
status: TodoStatus.todo,
title: 'create by socket.io',
});
const wsRes = await QueryTodo({});

console.log(wsRes);
setResult(wsRes);

io.disconnect();
setTimeout(async () => {
setXiorInstance(xior.create({ baseURL: apiURL }));
setHandler(xiorHandler);

setHanlderName(getHandler().name);
await AddTodo({
status: TodoStatus.todo,
title: 'create by axios',
});
const httpRes = await QueryTodo({});
console.log(httpRes);

setResult(httpRes);
}, 2500);
});

return () => {
io.off('connect');
};
}, []);

return (
<div className={styles.container}>
<Head>
<title>[web] Expo monorepo</title>
<meta name="description" content="Sharing code with Next.js" />
<link rel="icon" href="/favicon.ico" />
</Head>

<main className={styles.main}>
Hello, {handlerName}: {JSON.stringify(result)}
</main>
</div>
);
}
4 changes: 2 additions & 2 deletions packages/bench/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"change-case": "^4.1.2",
"express": "^4.18.2",
"zod": "^3.22.4",
"hono": "^3.10.2",
"hono": "^4.0.4",
"@hono/node-server": "^1.2.3",
"@trpc/server": "^10.44.1",
"fastify": "^4.24.3"
Expand All @@ -28,7 +28,7 @@
"@configs/test-config": "workspace:*",
"@configs/ts-config": "workspace:*",
"@configs/eslint-config": "workspace:*",
"@nestjs/cli": "^10.2.1",
"@nestjs/cli": "^10.3.2",
"@types/express": "^4.17.17",
"tsdk": "workspace:*",
"concurrently": "^8.2.2"
Expand Down
9 changes: 5 additions & 4 deletions packages/tsdk-server-adapters/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tsdk-server-adapters",
"version": "0.1.4",
"version": "0.1.5",
"main": "lib/index.js",
"repository": "tsdk-monorepo/tsdk",
"bugs": "https://github.com/tsdk-monorepo/tsdk/issues",
Expand All @@ -22,7 +22,8 @@
"express",
"socket.io",
"fastify",
"backend"
"backend",
"typesafe API"
],
"dependencies": {
"eventemitter3": "^4.0.7"
Expand All @@ -36,8 +37,8 @@
"peerDependencies": {
"express": "^4.18.2",
"zod": "^3",
"socket.io": "^4.7.2",
"hono": "^3.10.2",
"socket.io": "^4.7.4",
"hono": "^4.0.4",
"fastify": "^4.24.3"
},
"peerDependenciesMeta": {
Expand Down
3 changes: 2 additions & 1 deletion packages/tsdk-server-adapters/src/gen-route-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import EventEmitter from 'eventemitter3';
import type { Response } from 'express';
// @ts-ignore
import type { Context } from 'hono';
import { StatusCode, SuccessStatusCode } from 'hono/utils/http-status';

Check warning on line 7 in packages/tsdk-server-adapters/src/gen-route-factory.ts

View workflow job for this annotation

GitHub Actions / run-on-linux (18.x)

'SuccessStatusCode' is defined but never used

Check warning on line 7 in packages/tsdk-server-adapters/src/gen-route-factory.ts

View workflow job for this annotation

GitHub Actions / release (18.x)

'SuccessStatusCode' is defined but never used
// @ts-ignore
import type { Socket } from 'socket.io';
// @ts-ignore
Expand Down Expand Up @@ -67,7 +68,7 @@ function sendFactory(
(response as Response).status(status || 200).send(result);
} else if (protocol === 'hono') {
const { status, result } = payload;
(response as Context).status(status || 200);
(response as Context).status((status || 200) as StatusCode);
if (typeof result === 'string') {
callback?.((response as Context).text(result));
} else {
Expand Down
5 changes: 3 additions & 2 deletions packages/tsdk/fe-sdk-template/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
},
"dependencies": {
"zod": "^3",
"axios": "1.6.1",
"axios": "^1.6.7",
"xior": "^0.0.3",
"change-case": "^4.1.2"
},
"devDependencies": {
Expand All @@ -18,7 +19,7 @@
"@tsconfig/recommended": "^1.0.3"
},
"peerDependencies": {
"socket.io-client": "^4.7.2"
"socket.io-client": "^4.7.4"
},
"peerDependenciesMeta": {
"socket.io-client": {
Expand Down
3 changes: 2 additions & 1 deletion packages/tsdk/fe-sdk-template/src/gen-api.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { RequestConfig } from './axios';
import { NoHandlerError } from './error';
import { APIConfig, ObjectLiteral } from './shared/tsdk-helper';
import type { XiorRequestConfig } from './xior';

let handler = (
apiConfig: APIConfig,
requestData: any,
requestConfig?: RequestConfig<any> | ObjectLiteral,
requestConfig?: any | RequestConfig<any> | ObjectLiteral | XiorRequestConfig<any>,
needTrim?: boolean
): Promise<any> => {
return Promise.reject(new NoHandlerError(`Call \`setHandler\` first`));
Expand Down
1 change: 1 addition & 0 deletions packages/tsdk/fe-sdk-template/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './axios';
export * from './socket.io';
export * from './gen-api';
export * from './xior';
77 changes: 77 additions & 0 deletions packages/tsdk/fe-sdk-template/src/xior.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { XiorRequestConfig as _XiorRequestConfig, xior } from 'xior';

import { NoHandlerError } from './error';
import { pathParams } from './path-params';
import { APIConfig, checkMethodHasBody, trimAndRemoveUndefined } from './shared/tsdk-helper';

let xiorInstance: xior;

/**
* Set the XiorInstance
*
* @param instance - XiorInstance
*/
export const setXiorInstance = (instance: xior): void => {
xiorInstance = instance;
};

/**
* Get the XiorInstance
*
* @param instance - XiorInstance
* @returns The XiorInstance
*/
export const getXiorInstance = () => {
return xiorInstance;
};

export type XiorRequestConfig<ReqPayload> = Omit<_XiorRequestConfig, 'data'> & {
data?: ReqPayload;
};

export async function xiorHandler(
apiConfig: APIConfig,
requestData: any,
requestConfig?: XiorRequestConfig<any>,
/** remove fields with undefined */
needTrim?: boolean
) {
const xiorInstance = getXiorInstance();
if (!xiorInstance) {
throw new NoHandlerError(`Call \`setXiorInstance\` first`);
}
const { path, headers } = apiConfig;
const method = apiConfig.method.toLowerCase();

// TODO: remove & {url: string}
const payload: _XiorRequestConfig & { url: string } = {
method: method === 'patch' ? method.toUpperCase() : method,
url: path,
...requestConfig,
};

if (headers) {
payload.headers = {
...payload.headers,
...headers,
};
}

if (requestData) {
const data = needTrim ? trimAndRemoveUndefined(requestData) : requestData;
if (checkMethodHasBody(method)) {
payload.data = data;
if (requestConfig?.params) {
payload.params = requestConfig.params;
}
} else {
payload.params = requestConfig?.params ? { ...requestConfig.params, ...data } : data;
}
}
if (requestData && (apiConfig as any).paramsInUrl) {
payload.url = pathParams(path, requestData, (apiConfig as any).paramsInUrl);
}

const { data } = await xiorInstance.request(payload);
return data;
}
Loading

0 comments on commit f91c383

Please sign in to comment.