Skip to content

Commit

Permalink
Fixed issue with empty URLs and Response methods not available
Browse files Browse the repository at this point in the history
  • Loading branch information
frangeris committed Oct 4, 2024
1 parent c5be850 commit 149328b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
40 changes: 23 additions & 17 deletions src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,16 @@ export class Service<P> {
}

private build(path?: RequestPath<P>) {
if (!path) {
return "";
}

if (typeof path === "string") {
return path;
}

// build complex path
let url = this.resource;
if (!path) {
return url;
}

// build complex path
const { params, query } = path;
if (params) {
for (const k in params) {
Expand All @@ -63,24 +63,27 @@ export class Service<P> {
return url;
}

private async response<T>(request: Response): ServiceResponse<T> {
return {
...request,
data: (await request.json()) as T,
};
private async response<T>(res: Response): Promise<ServiceResponse<T>> {
const newRes = res.clone() as unknown as ServiceResponse<T>;
newRes.data = (await res.json()) as T;

return newRes;
}

// HTTP methods
async get<T>(path?: RequestPath<P>): ServiceResponse<T> {
const request = await this.request({
async get<T>(path?: RequestPath<P>) {
const response = await this.request({
path,
method: "get",
});

return this.response<T>(request);
return this.response<T>(response);
}

async post<T>(payload: any, path?: RequestPath<P>): ServiceResponse<T> {
async post<T>(
payload: any,
path?: RequestPath<P>
): Promise<ServiceResponse<T>> {
const request = await this.request({
path,
method: "post",
Expand All @@ -90,7 +93,10 @@ export class Service<P> {
return this.response<T>(request);
}

async put<T>(payload: any, path?: RequestPath<P>): ServiceResponse<T> {
async put<T>(
payload: any,
path?: RequestPath<P>
): Promise<ServiceResponse<T>> {
const request = await this.request({
path,
method: "put",
Expand All @@ -100,7 +106,7 @@ export class Service<P> {
return this.response<T>(request);
}

async delete<T>(path?: RequestPath<P>): ServiceResponse<T> {
async delete<T>(path?: RequestPath<P>): Promise<ServiceResponse<T>> {
const request = await this.request({
path,
method: "delete",
Expand All @@ -112,7 +118,7 @@ export class Service<P> {
async patch<T>(
ops: PatchOperation[],
path?: RequestPath<P>
): ServiceResponse<T> {
): Promise<ServiceResponse<T>> {
const request = await this.request({
path,
method: "patch",
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export type InitOptions = {

export type Services<T> = { [K in keyof T]: Service<T[K]> };

export type ServiceResponse<R> = Promise<Response & { data: R }>;
export type ServiceResponse<R> = { data: R } & Response;

export type RequestPath<P> =
| {
Expand Down

0 comments on commit 149328b

Please sign in to comment.