Skip to content

Commit

Permalink
perf(flat-server-api): make flat-server-api tree-shakable
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed Aug 22, 2022
1 parent b01ce1c commit 7d93ca7
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 87 deletions.
4 changes: 0 additions & 4 deletions packages/flat-server-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@
"scripts": {
"build": "tsc"
},
"peerDependencies": {
"axios": "0.x"
},
"devDependencies": {
"axios": "^0.26.1",
"prettier": "^2.3.0",
"typescript": "^4.6.2"
}
Expand Down
16 changes: 7 additions & 9 deletions packages/flat-server-api/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
export const FLAT_SERVER_BASE_URL = `https://${process.env.FLAT_SERVER_DOMAIN}`;

export const FLAT_SERVER_VERSIONS = {
V1: `${FLAT_SERVER_BASE_URL}/v1`,
} as const;
export const FLAT_SERVER_BASE_URL_V1 = `https://${process.env.FLAT_SERVER_DOMAIN}/v1`;

export const FLAT_SERVER_LOGIN = {
AGORA_CALLBACK: `${FLAT_SERVER_VERSIONS.V1}/login/agora/callback`,
GITHUB_CALLBACK: `${FLAT_SERVER_VERSIONS.V1}/login/github/callback?platform=web`,
GOOGLE_CALLBACK: `${FLAT_SERVER_VERSIONS.V1}/login/google/callback`,
WECHAT_CALLBACK: `${FLAT_SERVER_VERSIONS.V1}/login/weChat/web/callback`,
AGORA_CALLBACK: `https://${process.env.FLAT_SERVER_DOMAIN}/v1/login/agora/callback`,
GITHUB_CALLBACK: `https://${process.env.FLAT_SERVER_DOMAIN}/v1/login/github/callback?platform=web`,
GOOGLE_CALLBACK: `https://${process.env.FLAT_SERVER_DOMAIN}/v1/login/google/callback`,
WECHAT_CALLBACK: `https://${process.env.FLAT_SERVER_DOMAIN}/v1/login/weChat/web/callback`,
} as const;

export const FLAT_SERVER_USER_BINDING = {
GITHUB_CALLBACK: `${FLAT_SERVER_VERSIONS.V1}/login/github/callback/binding`,
WECHAT_CALLBACK: `${FLAT_SERVER_VERSIONS.V1}/user/binding/platform/wechat/web`,
GITHUB_CALLBACK: `https://${process.env.FLAT_SERVER_DOMAIN}/v1/login/github/callback/binding`,
WECHAT_CALLBACK: `https://${process.env.FLAT_SERVER_DOMAIN}/v1/user/binding/platform/wechat/web`,
} as const;

export enum Region {
Expand Down
4 changes: 2 additions & 2 deletions packages/flat-server-api/src/login.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Status } from "./constants";
import { post, postNotAuth, postRAW } from "./utils";
import { post, postNotAuth, requestFlatServer } from "./utils";

export interface LoginCheckPayload {}

Expand Down Expand Up @@ -160,7 +160,7 @@ export interface BindingProcessResult {

export async function bindingProcess(authUUID: string): Promise<BindingProcessResult> {
try {
const ret = await postRAW<BindingProcessPayload, {}>("user/binding/process", {
const ret = await requestFlatServer<BindingProcessPayload, {}>("user/binding/process", {
authUUID,
});
if (ret.status === Status.Process) {
Expand Down
2 changes: 1 addition & 1 deletion packages/flat-server-api/src/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export function listRooms(
type: ListRoomsType,
payload: ListRoomsPayload,
): Promise<ListRoomsResult> {
return post<undefined, ListRoomsResult>(`room/list/${type}`, undefined, payload);
return post<undefined, ListRoomsResult>(`room/list/${type}?page=${payload.page}`);
}

export interface JoinRoomPayload {
Expand Down
140 changes: 73 additions & 67 deletions packages/flat-server-api/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,117 +1,123 @@
import Axios, { AxiosRequestConfig } from "axios";
import { FLAT_SERVER_VERSIONS, Status } from "./constants";
import { FLAT_SERVER_BASE_URL_V1, Status } from "./constants";
import { ServerRequestError, RequestErrorCode } from "./error";

let authToken = localStorage.getItem("FlatAuthToken");
let authToken = /* @__PURE__*/ localStorage.getItem("FlatAuthToken");

export type FlatServerResponse<T> =
| {
status: Status.Success;
data: T;
}
| {
status: Status.Failed;
code: RequestErrorCode;
status: Status.Process;
data: T;
};

export type FlatServerRawResponseData<T> =
| FlatServerResponse<T>
| {
status: Status.Process;
data: T;
status: Status.Failed;
code: RequestErrorCode;
};

export function setFlatAuthToken(token: string): void {
authToken = token;
localStorage.setItem("FlatAuthToken", token);
}

export async function postRAW<Payload, Result>(
export async function requestFlatServer<TPayload, TResult>(
action: string,
payload: Payload,
params?: AxiosRequestConfig["params"],
token?: string,
): Promise<FlatServerRawResponseData<Result>> {
const config: AxiosRequestConfig = {
params,
};
payload?: TPayload,
init?: Partial<RequestInit>,
token: string | null = authToken,
): Promise<FlatServerResponse<TResult>> {
const headers = new Headers(init?.headers);
headers.set("accept", "application/json, text/plain, */*");
const config: RequestInit = { method: "POST", ...init, headers };

if (payload) {
config.body = JSON.stringify(payload);
headers.set("content-type", "application/json");
}

const Authorization = token || authToken;
if (!Authorization) {
throw new ServerRequestError(RequestErrorCode.NeedLoginAgain);
if (token) {
headers.set("authorization", "Bearer " + token);
}

config.headers = {
Authorization: "Bearer " + Authorization,
};
const response = await fetch(`${FLAT_SERVER_BASE_URL_V1}/${action}`, config);

const { data: res } = await Axios.post<FlatServerRawResponseData<Result>>(
`${FLAT_SERVER_VERSIONS.V1}/${action}`,
payload,
config,
);
if (!response.ok) {
// @TODO create a timeout error code
throw new ServerRequestError(RequestErrorCode.ServerFail);
}

const data: FlatServerRawResponseData<TResult> = await response.json();

if (res.status !== Status.Success && res.status !== Status.Process) {
throw new ServerRequestError(res.code);
if (data.status !== Status.Success && data.status !== Status.Process) {
throw new ServerRequestError(data.code);
}

return res;
return data;
}

export async function post<Payload, Result>(
export async function post<TPayload, TResult>(
action: string,
payload: Payload,
params?: AxiosRequestConfig["params"],
payload?: TPayload,
init?: Partial<RequestInit>,
token?: string,
): Promise<Result> {
const res = await postRAW<Payload, Result>(action, payload, params, token);
if (res.status !== Status.Success) {
if (res.status === Status.Process) {
throw new TypeError(`[Flat API] ${action} returns unexpected processing status`);
} else {
throw new ServerRequestError(res.code);
): Promise<TResult> {
const authorization = token || authToken;
if (!authorization) {
throw new ServerRequestError(RequestErrorCode.NeedLoginAgain);
}
const res = await requestFlatServer<TPayload, TResult>(action, payload, init, authorization);

if (process.env.NODE_ENV !== "production") {
if (res.status !== Status.Success) {
throw new TypeError(
`[Flat API] ${action} returns unexpected processing status: ${res.status}`,
);
}
}

return res.data;
}

export async function postNotAuth<Payload, Result>(
export async function postNotAuth<TPayload, TResult>(
action: string,
payload: Payload,
params?: AxiosRequestConfig["params"],
): Promise<Result> {
const config: AxiosRequestConfig = {
params,
};

const { data: res } = await Axios.post<FlatServerResponse<Result>>(
`${FLAT_SERVER_VERSIONS.V1}/${action}`,
payload,
config,
);

if (res.status !== Status.Success) {
throw new ServerRequestError(res.code);
payload?: TPayload,
init?: Partial<RequestInit>,
): Promise<TResult> {
const res = await requestFlatServer<TPayload, TResult>(action, payload, init, "");

if (process.env.NODE_ENV !== "production") {
if (res.status !== Status.Success) {
throw new TypeError(
`[Flat API] ${action} returns unexpected processing status: ${res.status}`,
);
}
}

return res.data;
}

export async function getNotAuth<Result>(
export async function getNotAuth<TResult>(
action: string,
params?: AxiosRequestConfig["params"],
): Promise<Result> {
const config: AxiosRequestConfig = {
params,
};

const { data: res } = await Axios.get<FlatServerResponse<Result>>(
`${FLAT_SERVER_VERSIONS.V1}/${action}`,
config,
init?: Partial<RequestInit>,
): Promise<TResult> {
const res = await requestFlatServer<undefined, TResult>(
action,
undefined,
{ ...init, method: "GET" },
"",
);

if (res.status !== Status.Success) {
throw new ServerRequestError(res.code);
if (process.env.NODE_ENV !== "production") {
if (res.status !== Status.Success) {
throw new TypeError(
`[Flat API] ${action} returns unexpected processing status: ${res.status}`,
);
}
}

return res.data;
Expand Down
12 changes: 8 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 7d93ca7

Please sign in to comment.