Skip to content

Commit 329ff3c

Browse files
Added statuscode parseData method of Route
1 parent 8f3e019 commit 329ff3c

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

src/routes/Route.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ export abstract class Route<T> {
8888
* Fetch the raw data from the url
8989
* @returns The data from the API
9090
*/
91-
private async fetchRaw(): Promise<any> {
91+
private async fetchRaw(): Promise<Response> {
9292
return fetch(this.getUrl().toString(), {
9393
method: this.getFetchMethod(),
9494
headers: {
@@ -97,22 +97,15 @@ export abstract class Route<T> {
9797
'Content-Type': this.getFetchBody()?.getContentType() ?? '',
9898
},
9999
body: this.getFetchBody()?.getFormattedBody() ?? undefined,
100-
})
101-
.then((res) => {
102-
if (res.status === 404) {
103-
return null;
104-
}
105-
106-
return res.json();
107-
})
108-
.then((data) => data);
100+
});
109101
}
110102

111103
/**
112104
* Parse the data from the API
113105
* @param data The data from the API
106+
* @param statusCode The status code of the response
114107
*/
115-
abstract parseData(data: any): T;
108+
abstract parseData(data: any, statusCode: number): T;
116109

117110
/**
118111
* Get the data from the API
@@ -126,12 +119,21 @@ export abstract class Route<T> {
126119
}
127120
}
128121

129-
const data = this.parseData(await this.fetchRaw());
122+
const res = await this.fetchRaw();
123+
124+
let rawData: any | null = null;
125+
try {
126+
rawData = await res.json();
127+
} catch (error) {
128+
rawData = null;
129+
}
130+
131+
const parsedData = this.parseData(rawData, res.status);
130132

131133
if (this.cacheManager.isEnabled() && this.getCacheKey() != null)
132-
this.cacheManager.set(this.getCacheKey()!!, data);
134+
this.cacheManager.set(this.getCacheKey()!!, parsedData);
133135

134-
return data;
136+
return parsedData;
135137
}
136138

137139
public static addPathSegment(url: URL, pathSegment: string): URL {

0 commit comments

Comments
 (0)