Skip to content

Commit

Permalink
feat: add custom request module
Browse files Browse the repository at this point in the history
  • Loading branch information
animify committed Feb 9, 2020
1 parent cde2c1e commit 0f5816d
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 1 deletion.
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,8 @@
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},
"dependencies": {
"whatwg-fetch": "^3.0.0"
}
}
}
62 changes: 62 additions & 0 deletions src/Request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import 'whatwg-fetch';

interface FetchOptions {
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
url: string;
body?: Record<string, any>;
}

export default class Request {
private static _accessToken: string | undefined;

public static async fetch(opts: FetchOptions) {
try {
const response = await fetch(Request.buildURL(opts.url), {
method: opts.method,
body: JSON.stringify(opts.body),
headers: {
Authorization: `Bearer ${Request.accessToken}`,
},
});

Request.checkStatus(response);

return await Request.parseResponse(response);
} catch (error) {
throw error;
}
}

public static get accessToken() {
if (!Request._accessToken) {
throw new Error('Access token is not defined.');
}

return Request._accessToken;
}

public static set accessToken(token: string) {
Request._accessToken = token;
}

private static buildURL(url: string) {
return `https://api.dribbble.com/v2/${url}`.replace(/([^:]\/)\/+/g, '$1');
}

private static checkStatus(response: Response) {
if (response.status === 200) return;

let message = response.statusText;

switch (response.status) {
case 400:
message = 'Something went wrong 400';
}

throw new Error(message);
}

private static parseResponse(response: Response) {
return response.json();
}
}
Empty file added src/index.ts
Empty file.
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3006,6 +3006,11 @@ validate-npm-package-license@^3.0.1:
spdx-correct "^3.0.0"
spdx-expression-parse "^3.0.0"

whatwg-fetch@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.0.0.tgz#fc804e458cc460009b1a2b966bc8817d2578aefb"
integrity sha512-9GSJUgz1D4MfyKU7KRqwOjXCXTqWdFNvEr7eUBYchQiVc744mqK/MzXPNR2WsPkmkOa4ywfg8C2n8h+13Bey1Q==

which@^1.2.10, which@^1.2.9:
version "1.3.1"
resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"
Expand Down

0 comments on commit 0f5816d

Please sign in to comment.