강력한 API 타입 체크

This commit is contained in:
2023-08-06 09:27:24 +00:00
parent 7352cdbf23
commit 826b4212e5
11 changed files with 266 additions and 445 deletions
+32 -19
View File
@@ -1,22 +1,8 @@
import type { Request, Response } from 'express';
export interface ValidResponse {
result: true;
}
export type recoveryMethod = 'refreshEntirePage' | 'retryAPI' | 'gameLogin' | 'gatewayLogin' | 'gatewayPIN';
export interface InvalidResponse {
result: false;
reason: string;
recovery?: recoveryMethod;
}
import type { APICallT, Callable, DefAPINamespace, EmptyAPICallT, HttpMethod, InvalidResponse, RawArgType, ValidResponse, recoveryMethod } from '../apiStructure/defs';
export const treatedSpecial = Symbol('treatedSpecial');
export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head';
export type RawArgType = Record<string, unknown> | Record<string, unknown>[] | undefined;
export type APINamespace = {
[key: string]: APINamespace
| GET<any, any, any>
@@ -29,14 +15,14 @@ export type APINamespace = {
}
export abstract class APIExecuter<R extends ValidResponse, E extends InvalidResponse, Q extends RawArgType>{
readonly abstract reqType: HttpMethod | HttpMethod[];
readonly abstract reqType: HttpMethod;
protected abstract parseQuery(expressReq: Request): Promise<Q>;
protected abstract api(query: Q, expressReq: Request, expressRes: Response): Promise<R | E | typeof treatedSpecial>;
protected abstract api(query: Q, expressReq: Request, expressRes: Response): Promise<R | E | true>;
public async run(expressReq: Request, expressRes: Response): Promise<void> {
const query = await this.parseQuery(expressReq);
//TODO: middleware (인증, 요구사항, 아마도 decorator)
const result = await this.api(query, expressReq, expressRes);
if (result === treatedSpecial) {
if (result === true) {
return;
}
expressRes.json(result);
@@ -77,4 +63,31 @@ export abstract class PATCH<R extends ValidResponse, E extends InvalidResponse,
export abstract class HEAD<R extends ValidResponse, E extends InvalidResponse, Q extends RawArgType> extends APIBodyParseExecuter<R, E, Q>{
readonly reqType = 'head';
}
}
export function raiseError(reason: string, recovery?: recoveryMethod): InvalidResponse {
if (recovery) {
return {
result: false,
reason,
recovery,
};
}
return {
result: false,
reason,
};
}
export type GetClassGenerator<T> = {
prototype: T
};
export type APIServerType<T extends Callable> =
T extends APICallT<infer Q, infer R, infer E> ? GetClassGenerator<APIExecuter<R, E, Q>> :
never;
export type APINamespaceType<T extends DefAPINamespace> = {
[K in keyof T]:
T[K] extends Callable ? APIServerType<T[K]> :
T[K] extends DefAPINamespace ? APINamespaceType<T[K]> :
never;
};