Skip to content

Commit

Permalink
#38
Browse files Browse the repository at this point in the history
- deps: обновлен @humanwhocodes/env для правок ts (minor)
- http: eitherResponse теперь позволяет переопределить парсер боди, по умолчанию пытается распарсить json (minor)
  • Loading branch information
krutoo committed Jun 14, 2024
1 parent 306c8a6 commit 005784c
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 44 deletions.
42 changes: 21 additions & 21 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"whatwg-fetch": "^3.6.17"
},
"dependencies": {
"@humanwhocodes/env": "^3.0.2",
"@humanwhocodes/env": "^3.0.5",
"@krutoo/fetch-tools": "^0.0.16",
"@opentelemetry/api": "^1.4.1",
"@opentelemetry/exporter-prometheus": "^0.38.0",
Expand Down
2 changes: 0 additions & 2 deletions src/config/source.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import type { ConfigSource, Dictionary } from './types';

// @ts-expect-error: https://github.com/humanwhocodes/env/issues/133 (@todo разобраться и убрать)
import { Env } from '@humanwhocodes/env';

declare const __ISOMORPH_ENV__: unknown;
Expand Down
5 changes: 4 additions & 1 deletion src/http/__test__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,16 @@ describe('FetchUtil', () => {
error: null,
status: 200,
statusText: 'GOOD',
headers: new Headers({ 'content-type': 'text/plain;charset=UTF-8' }),
});

expect(await handleDone(responseFail)).toEqual({
ok: false,
error: `Request failed with status 400`,
data: { data: 'bar' },
error: new Error(`Request failed with status code 400`),
status: 400,
statusText: 'BAD',
headers: new Headers({ 'content-type': 'text/plain;charset=UTF-8' }),
});

const error = new Error('Fetch failed');
Expand Down
2 changes: 2 additions & 0 deletions src/http/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface ResponseDone<T = unknown> {
error: null;
status: number;
statusText: string;
headers: Headers;
}

export interface ResponseFail<T = unknown> {
Expand All @@ -27,6 +28,7 @@ export interface ResponseFail<T = unknown> {
error: unknown;
status?: number;
statusText?: string;
headers?: Headers;
}

export type EitherResponse<T> = ResponseDone<T> | ResponseFail<T>;
Expand Down
46 changes: 27 additions & 19 deletions src/http/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,33 +55,41 @@ export const FetchUtil = {
/**
* Возвращает кортеж обработчиков для Promise из fetch.
* Полученный Promise никогда не уйдет в состояние rejected.
* @param options Опции.
* @return Кортеж.
*/
eitherResponse<T = unknown>() {
eitherResponse<T = unknown>({
parseBody = response => response.json(),
}: {
/** Парсер body. */
parseBody?: (response: Response) => Promise<T>;
} = {}) {
return [
(response: Response): Promise<ResponseDone<T> | ResponseFail<T>> => {
if (response.ok) {
return response.json().then(data => ({
ok: true,
data: data as T,
error: null,
status: response.status,
statusText: response.statusText,
}));
} else {
return Promise.resolve({
async (response: Response): Promise<ResponseDone<T> | ResponseFail<T>> => {
if (!response.ok) {
return {
ok: false,
error: `Request failed with status ${response.status}`,
data: (await parseBody(response).catch(() => null)) as T,
error: new Error(`Request failed with status code ${response.status}`),
status: response.status,
statusText: response.statusText,
});
headers: response.headers,
};
}

return {
ok: true,
data: (await parseBody(response).catch(() => null)) as T,
error: null,
status: response.status,
statusText: response.statusText,
headers: response.headers,
};
},
(error: unknown): Promise<ResponseFail<T>> =>
Promise.resolve({
ok: false,
error,
}),
async (error: unknown): Promise<ResponseFail<T>> => ({
ok: false,
error,
}),
] as const;
},
} as const;

0 comments on commit 005784c

Please sign in to comment.