refactor: ape client types

fully type query, payload and return data with generics
This commit is contained in:
Miodec 2024-02-14 17:29:52 +01:00
parent 69683494e3
commit c04458cb90
2 changed files with 32 additions and 21 deletions

View file

@ -14,8 +14,8 @@ type AxiosClientDataMethod = (
config: AxiosRequestConfig
) => Promise<AxiosResponse>;
async function adaptRequestOptions(
options: Ape.RequestOptions
async function adaptRequestOptions<TQuery, TPayload>(
options: Ape.RequestOptionsWithPayload<TQuery, TPayload>
): Promise<AxiosRequestConfig> {
const idToken = isAuthenticated()
? await getIdToken(getAuthenticatedUser())
@ -37,11 +37,11 @@ async function adaptRequestOptions(
function apeifyClientMethod(
clientMethod: AxiosClientMethod | AxiosClientDataMethod,
methodType: Ape.HttpMethodTypes
): Ape.HttpClientMethod {
return async (
): Ape.HttpClientMethod | Ape.HttpClientMethodWithPayload {
return async function <TQuery, TPayload, TData>(
endpoint: string,
options: Ape.RequestOptions = {}
): Ape.EndpointResponse => {
options: Ape.RequestOptionsWithPayload<TQuery, TPayload> = {}
): Ape.EndpointResponse<TData> {
let errorMessage = "";
try {

View file

@ -1,29 +1,40 @@
declare namespace Ape {
type RequestOptions = {
type RequestOptions<TQuery> = {
headers?: Record<string, string>;
searchQuery?: Record<string, any>;
payload?: any;
searchQuery?: Record<string, TQuery>;
};
type HttpClientResponse<Data> = {
type HttpClientMethod = <TQuery, TData>(
endpoint: string,
options?: Ape.RequestOptions<TQuery>
) => Ape.EndpointResponse<TData>;
type RequestOptionsWithPayload<TQuery, TPayload> = {
headers?: Record<string, string>;
searchQuery?: Record<string, TQuery>;
payload?: TPayload;
};
type HttpClientMethodWithPayload = <TQuery, TPayload, TData>(
endpoint: string,
options?: Ape.RequestOptionsWithPayload<TQuery, TPayload>
) => Ape.EndpointResponse<TData>;
type HttpClientResponse<TData> = {
status: number;
message: string;
data: Data | null;
data: TData | null;
};
type EndpointResponse<Data = any> = Promise<HttpClientResponse<Data>>;
type HttpClientMethod<Data = any> = (
endpoint: string,
config?: RequestOptions
) => EndpointResponse<Data>;
// todo: remove any after all ape endpoints are typed
type EndpointResponse<TData = any> = Promise<HttpClientResponse<TData>>;
type HttpClient = {
get: HttpClientMethod;
post: HttpClientMethod;
put: HttpClientMethod;
patch: HttpClientMethod;
delete: HttpClientMethod;
post: HttpClientMethodWithPayload;
put: HttpClientMethodWithPayload;
patch: HttpClientMethodWithPayload;
delete: HttpClientMethodWithPayload;
};
type HttpMethodTypes = keyof HttpClient;