Skip to content

Commit

Permalink
feat(client-request.ts): add error handling to get method and create …
Browse files Browse the repository at this point in the history
…IResponseError interface

refactor(client-request.ts): make params parameter more generic in get method
  • Loading branch information
mdwitr0 committed Jun 22, 2023
1 parent 610faab commit b91c057
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 9 deletions.
43 changes: 34 additions & 9 deletions src/client-request.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,45 @@
import { VERSIONS } from './enums/version.enum';
import { IResponseError } from './interfaces/error.interface';

export class ClientRequest {
constructor(
private readonly API_KEY: string,
private readonly API_URL: string,
) {}

async get<T, P>(version: VERSIONS, path: string, params?: P): Promise<T> {
const response = await fetch(
`${this.API_URL}/${version}${path}?${new URLSearchParams(params || {})}`,
{
headers: {
'X-API-KEY': this.API_KEY,
async get<T, P extends Record<string, unknown>>(
version: VERSIONS,
path: string,
params?: P,
): Promise<T | IResponseError> {
try {
const response = await fetch(
`${this.API_URL}/${version}${path}?${new URLSearchParams(
params as any,
)}`,
{
headers: {
'X-API-KEY': this.API_KEY,
},
},
},
);
return await response.json();
);

// If the HTTP response status is not 200, throw an error
if (!response.ok) {
const error: IResponseError = await response.json();
throw new Error(
`HTTP error! status: ${response.status}, error: ${error.error}, message: ${error.message}`,
);
}

return await response.json();
} catch (error) {
console.error('There was an error with your request:', error);
return {
statusCode: error.status,
error: error.error,
message: error.message,
} as IResponseError;
}
}
}
14 changes: 14 additions & 0 deletions src/interfaces/error.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { MovieService } from '../services/movie.service';
import { SeasonService } from '../services/season.service';
import { PersonService } from '../services/person.service';
import { ReviewService } from '../services/review.service';
import { KeywordService } from '../services/keyword.service';
import { StudioService } from '../services/studio.service';
import { ImageService } from '../services/image.service';
import { ClientRequest } from '../client-request';

export interface IResponseError {
statusCode: number;
message: string;
error: string;
}

0 comments on commit b91c057

Please sign in to comment.