Skip to content
This repository has been archived by the owner on Dec 11, 2024. It is now read-only.

Commit

Permalink
feat(export): nova isntancia padrão e error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
andrefelipeschulle committed Feb 6, 2024
1 parent 08bd8be commit 8dc3c82
Show file tree
Hide file tree
Showing 16 changed files with 515 additions and 349 deletions.
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"cSpell.words": [
"fwpr",
"fwrp"
]
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@brainylab/fetch-wrapper",
"version": "0.2.1",
"version": "0.3.0",
"main": "./index.js",
"module": "./index.mjs",
"types": "./index.d.ts",
Expand Down Expand Up @@ -31,7 +31,7 @@
},
"license": "MIT",
"devDependencies": {
"@brainylab/eslint-config": "^1.0.14",
"@brainylab/eslint-config": "^1.0.20",
"@commitlint/config-conventional": "^18.6.0",
"@evilmartians/lefthook": "^1.6.1",
"@types/node": "^20.11.16",
Expand Down
613 changes: 317 additions & 296 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

12 changes: 0 additions & 12 deletions src/create-instance.spec.ts

This file was deleted.

12 changes: 0 additions & 12 deletions src/create-instance.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HttpRequestError } from './http-error';
import { HttpRequestError } from './http-request-error';

describe('http-request-error', () => {
it('should be http error', () => {
Expand Down
File renamed without changes.
15 changes: 15 additions & 0 deletions src/fwpr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { FetchWrapperProps } from './lib/create-instance';
import { createInstance } from './lib/create-instance';
import type { ErrorHandlingResponse } from './lib/error-handling';
import { fwprErrorHandling } from './lib/error-handling';
import type { FetchWrapper } from './lib/fetch-wrapper';

const fwpr = createInstance() as FetchWrapper & {
create: (defaultConfig?: FetchWrapperProps) => FetchWrapper;
errorHandling: (error: unknown) => ErrorHandlingResponse;
};

fwpr.create = createInstance;
fwpr.errorHandling = fwprErrorHandling;

export default fwpr;
19 changes: 10 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { create } from './create-instance';

const wrapper = { create };

export { wrapper };
export default wrapper;

export * from './http-error';
import fwpr from './fwpr';

/**
* exports types
*/
export type { FetchWrapperProps } from './create-instance';
export type { FetchWrapperProps } from './lib/create-instance';

/**
* export lib
*/
export * from './errors/http-request-error';
export * from './lib/error-handling';

export { fwpr as default, fwpr };
21 changes: 21 additions & 0 deletions src/lib/create-instance.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { fwpr } from '../index';
import { createInstance } from './create-instance';
import { FetchWrapper } from './fetch-wrapper';

describe('create-instance', () => {
it('should create an instance of FetchWrapper', () => {
const api = createInstance({
baseUrl: 'http://localhost:3000',
});

expect(api).toBeInstanceOf(FetchWrapper);
});

it('should create an instance of FetchWrapper using index.js', () => {
const api = fwpr.create({
baseUrl: 'http://localhost:3000',
});

expect(api).toBeInstanceOf(FetchWrapper);
});
});
13 changes: 13 additions & 0 deletions src/lib/create-instance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { FetchWrapperDefaults } from './fetch-wrapper';
import { FetchWrapper } from './fetch-wrapper';

export type FetchWrapperProps = {
baseUrl?: string;
defaultConfig?: FetchWrapperDefaults;
};

export function createInstance(defaultConfig?: FetchWrapperProps) {
const instance = new FetchWrapper(defaultConfig);

return instance;
}
38 changes: 38 additions & 0 deletions src/lib/error-handling.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { HttpRequestError } from '../errors/http-request-error';
import fwpr from '../fwpr';
import { fwprErrorHandling } from './error-handling';

describe('error-handling', () => {
it('should handle HttpRequestError', async () => {
const error = fwprErrorHandling(
new HttpRequestError({
status: 404,
statusText: 'Not Found',
} as Response),
);

expect(error).toHaveProperty('error');
expect(error.error).toEqual('HTTP_REQUEST_ERROR');
});

it('should handle ECONNREFUSED error', async () => {
try {
await fwpr.get('http://localhost');
} catch (error) {
const result = fwprErrorHandling(error);

console.log(error);

expect(result).toHaveProperty('error');
expect(result.error).toEqual('CONNECTION_REFUSED');
}
});

it('should handle unknown error', () => {
const error = { code: 'UNKNOWN_ERROR' };
const result = fwprErrorHandling(error);

expect(result).toHaveProperty('error');
expect(result.error).toEqual('UNEXPECTED_ERROR');
});
});
40 changes: 40 additions & 0 deletions src/lib/error-handling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { HttpRequestError } from '../errors/http-request-error';

type FetchTypeError = TypeError & {
cause?: { code: 'ECONNREFUSED'; address: string; port: number };
};

export type ErrorHandlingResponse = {
status?: number;
message: string;
error: 'HTTP_REQUEST_ERROR' | 'CONNECTION_REFUSED' | 'UNEXPECTED_ERROR';
throw?: unknown;
};

export function fwprErrorHandling(error: unknown): ErrorHandlingResponse {
console.log(error);
if (error instanceof HttpRequestError) {
return {
status: error.status,
message: error.message,
error: 'HTTP_REQUEST_ERROR',
};
}

if (error instanceof TypeError) {
const err = error as FetchTypeError;

if (err?.cause && err?.cause.code === 'ECONNREFUSED') {
return {
message: `connection refused ${err.cause.address} on port ${err.cause.port}`,
error: 'CONNECTION_REFUSED',
};
}
}

return {
message: 'an unexpected error occurred',
error: 'UNEXPECTED_ERROR',
throw: error,
};
}
38 changes: 38 additions & 0 deletions src/lib/fetch-wrapper.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { HttpRequestError } from '../errors/http-request-error';
import { fwprErrorHandling } from '../lib/error-handling';
import { FetchWrapper } from './fetch-wrapper';

describe('fetch-wrapper', () => {
let api: FetchWrapper;

beforeEach(() => {
api = new FetchWrapper();
});

it('should be able to make a GET request', async () => {
const response = await api.get('https://api.github.com/orgs/brainylab');

expect(response.status).toBe(200);
expect(response.statusText).toBe('OK');
expect(typeof response.data).toBe('object');
expect(response.data).toHaveProperty('id');
});

it('should be able to return an HttpRequestError error on a request', async () => {
try {
await api.get('https://api.github.com/orgs');
} catch (err) {
expect(err).toBeInstanceOf(HttpRequestError);
}
});

it('should be able to return an HttpRequestError error on a request connection refused', async () => {
try {
await api.get('http://localhost');
} catch (err) {
const { error } = fwprErrorHandling(err);

expect(error).toBe('CONNECTION_REFUSED');
}
});
});
29 changes: 14 additions & 15 deletions src/fetch-wrapper.ts → src/lib/fetch-wrapper.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { FetchWrapperProps } from './create-instance';
import { HttpRequestError } from './http-error';
import { createPath } from './utils/create-path';
import { mergeConfigs } from './utils/merge-configs';
import { objectToUrlParams } from './utils/object-to-url-params';
import { HttpRequestError } from '../errors/http-request-error';
import { createPath } from '../utils/create-path';
import { mergeConfigs } from '../utils/merge-configs';
import { objectToUrlParams } from '../utils/object-to-url-params';
import type { FetchWrapperProps } from './create-instance';

export type FetchWrapperDefaults = {
headers: HeadersInit & { Authorization?: string };
Expand All @@ -17,7 +17,7 @@ type FetchWrapperResponse<T> = {
data: T;
};

interface FetchMethods {
type FetchMethods = {
get: <T>(
path: string | string[],
init?: FetchWrapperInit,
Expand All @@ -36,27 +36,26 @@ interface FetchMethods {
path: string | string[],
init?: FetchWrapperInit,
) => Promise<FetchWrapperResponse<T>>;
}
};

export class FetchWrapper implements FetchMethods {
private url: string;
private url: string = 'http://localhost';
public defaults: FetchWrapperDefaults = {
headers: {
Accept: 'application/json',
'Content-type': 'application/json; charset=UTF-8',
},
};

constructor({
baseUrl = 'http://localhost',
defaultConfig,
}: FetchWrapperProps) {
this.url = baseUrl;
constructor(props?: FetchWrapperProps) {
if (props?.baseUrl) {
this.url = props.baseUrl;
}

if (defaultConfig) {
if (props?.defaultConfig) {
this.defaults = mergeConfigs(
this.defaults,
defaultConfig,
props.defaultConfig,
) as FetchWrapperDefaults;
}
}
Expand Down
2 changes: 0 additions & 2 deletions src/utils/merge-configs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ describe('merge-configs', () => {
const newConfig = { b: 3, c: { b: 5 } };
const result = mergeConfigs(defaultConfig, newConfig);

console.log(result);

expect(result).toEqual({
a: 1,
b: 3,
Expand Down

0 comments on commit 8dc3c82

Please sign in to comment.