Skip to content

Instantly share code, notes, and snippets.

@Hoyasumii
Last active August 23, 2024 14:41
Show Gist options
  • Save Hoyasumii/328c43e65af89b310d733cb224f77fc9 to your computer and use it in GitHub Desktop.
Save Hoyasumii/328c43e65af89b310d733cb224f77fc9 to your computer and use it in GitHub Desktop.
HttpRequester for @elysiajs/eden
import { edenFetch } from "@elysiajs/eden";
export interface BaseResponse<T = any> {
success: boolean;
message?: string;
data?: T;
}
export interface ServiceResponse<T = any> {
status: number;
data: BaseResponse<T>;
}
class HttpRequest {
private fetch;
public baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
this.fetch = edenFetch(this.baseUrl);
}
async get(
path: string,
headers?: Record<string, string>
): Promise<ServiceResponse> {
const { data, error, status } = await this.fetch(path as any, {
method: "GET",
headers,
params: undefined,
query: undefined,
body: undefined,
});
return {
status,
data: error?.value ?? data,
};
}
async post<T extends Object>(
path: string,
body: T,
headers?: Record<string, string>
): Promise<ServiceResponse> {
const { data, error, status } = await this.fetch(path as any, {
method: "POST",
body,
headers,
params: undefined,
query: undefined,
});
return {
status,
data: error?.value ?? data,
};
}
async put<T extends Object>(
path: string,
body: T,
headers?: Record<string, string>
): Promise<ServiceResponse> {
const { data, error, status } = await this.fetch(path as any, {
method: "PUT",
headers,
body,
params: undefined,
query: undefined,
});
return {
status,
data: error?.value ?? data,
};
}
async patch<T extends Object>(
path: string,
body: Partial<T>,
headers?: Record<string, string>
): Promise<ServiceResponse> {
const { data, error, status } = await this.fetch(path as any, {
method: "PATCH",
headers,
body,
params: undefined,
query: undefined,
});
return {
status,
data: error?.value ?? data,
};
}
async delete(
path: string,
headers?: Record<string, string>
): Promise<ServiceResponse> {
const { data, error, status } = await this.fetch(path as any, {
method: "DELETE",
headers,
body: undefined,
params: undefined,
query: undefined,
});
return {
status,
data: error?.value ?? data,
};
}
}
export const Requester = (baseUrl: string) => new HttpRequest(baseUrl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment