feat: ts APICall을 강제화.
- 오버 엔지니어링의 정석
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import axios from "axios";
|
||||
import { isArray } from "lodash";
|
||||
import { InvalidResponse } from '@/defs';
|
||||
|
||||
export type ValidResponse = {
|
||||
result: true
|
||||
}
|
||||
|
||||
export async function callSammoAPI<ResultType extends ValidResponse>(path: string | string[], args?: Record<string, unknown>): Promise<ResultType>;
|
||||
export async function callSammoAPI<ResultType extends ValidResponse>(path: string | string[], args: Record<string, unknown> | undefined, returnError: false): Promise<ResultType>;
|
||||
export async function callSammoAPI<ResultType extends ValidResponse, ErrorType extends InvalidResponse>(path: string | string[], args: Record<string, unknown> | undefined, returnError: true): Promise<ResultType | ErrorType>;
|
||||
|
||||
export async function callSammoAPI<ResultType extends ValidResponse, ErrorType extends InvalidResponse>(path: string | string[], args?: Record<string, unknown>, returnError = false): Promise<ResultType | ErrorType> {
|
||||
if (isArray(path)) {
|
||||
path = path.join('/');
|
||||
}
|
||||
|
||||
const response = await axios({
|
||||
url: "api.php",
|
||||
method: "post",
|
||||
responseType: "json",
|
||||
data: {
|
||||
path,
|
||||
args,
|
||||
},
|
||||
});
|
||||
const result: ErrorType | ResultType = response.data;
|
||||
if (!result.result) {
|
||||
if (returnError) {
|
||||
return result;
|
||||
}
|
||||
throw result.reason;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Reference in New Issue
Block a user