Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Шаг 84 #38 Правки утилит для fetch #135

Merged
merged 3 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
1 change: 0 additions & 1 deletion src/config/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @ts-expect-error: https://github.com/humanwhocodes/env/issues/133 (@todo разобраться и убрать)
import type { Env } from '@humanwhocodes/env';

/** Источник конфигурации. */
Expand Down
28 changes: 27 additions & 1 deletion src/http/__test__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,20 +84,46 @@ describe('FetchUtil', () => {

const responseDone = new Response('{ "data": "foo" }', { status: 200, statusText: 'GOOD' });
const responseFail = new Response('{ "data": "bar" }', { status: 400, statusText: 'BAD' });
const responseInvalidJson = new Response('{ aaAA }', { status: 200, statusText: 'INVALID' });
const responseFailInvalidJson = new Response('{ aaAA }', {
status: 400,
statusText: 'INVALID',
});

expect(await handleDone(responseDone)).toEqual({
ok: true,
data: { data: 'foo' },
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' }),
});

expect(await handleDone(responseInvalidJson)).toEqual({
ok: true,
data: null,
error: null,
status: 200,
statusText: 'INVALID',
headers: new Headers({ 'content-type': 'text/plain;charset=UTF-8' }),
});

expect(await handleDone(responseFailInvalidJson)).toEqual({
ok: false,
data: null,
error: new Error(`Request failed with status code ${400}`),
status: 400,
statusText: 'INVALID',
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;
Loading