From 0f5816dd70dffe5d0c05dff97ee9829608347012 Mon Sep 17 00:00:00 2001 From: Stefan Mansson Date: Sun, 9 Feb 2020 18:55:19 +0100 Subject: [PATCH] feat: add custom request module --- package.json | 5 +++- src/Request.ts | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 0 yarn.lock | 5 ++++ 4 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 src/Request.ts create mode 100644 src/index.ts diff --git a/package.json b/package.json index 9437783..2ab786c 100644 --- a/package.json +++ b/package.json @@ -48,5 +48,8 @@ "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" + }, + "dependencies": { + "whatwg-fetch": "^3.0.0" } -} \ No newline at end of file +} diff --git a/src/Request.ts b/src/Request.ts new file mode 100644 index 0000000..988fa9c --- /dev/null +++ b/src/Request.ts @@ -0,0 +1,62 @@ +import 'whatwg-fetch'; + +interface FetchOptions { + method: 'GET' | 'POST' | 'PUT' | 'DELETE'; + url: string; + body?: Record; +} + +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(); + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..e69de29 diff --git a/yarn.lock b/yarn.lock index 19293fb..1a81040 100644 --- a/yarn.lock +++ b/yarn.lock @@ -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"