Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // host url
- const host = 'http://localhost:3030';
- // function accepts Method, url (not host) and data (Object - {})
- async function request(method, url, data) {
- // creating options
- const options = {
- method,
- headers: {},
- };
- // if there is no data then don't do the next step, 'cause you won't need it
- if (data != undefined) {
- options.headers['Content-Type'] = 'application/json';
- options.body = JSON.stringify(data);
- }
- // get user information from Local Storage
- const user = JSON.parse(localStorage.getItem('user'));
- if (user) {
- // Get Access Token and put it into the header
- const token = user.accessToken;
- options.headers['X-Authorization'] = token;
- };
- // try the fetch, if fails throw an Error and catch it
- try {
- // getting response
- const response = await fetch(host + url, options);
- // if response status isn't OK (a.k.a. status != 200) throw an error
- if (response.ok !== true) {
- if (response.status == 403) localStorage.removeItem('user');
- const error = await response.json();
- throw new Error(error.message);
- }
- // check if status is == 204, if true then return only the response, otherways return response.json()
- // logging out returns an object, which if tried to be parsed from JSON will throw an error (CHECK SERVER DOCUMENTATION!!)
- if (response.status == 204) {
- return response;
- } else {
- return response.json();
- }
- } catch (error) {
- // If Error is thrown, throw it again... like the hot ball game.. (a.k.a. Goresht Kartoff)...
- // so the function using the api would be able to decide what to do with that exact error (show it to the User or sth else)
- // alert(error.message);
- throw error;
- }
- }
- // creating copies for all the methods
- const get = request.bind(null, 'get');
- const post = request.bind(null, 'post');
- const put = request.bind(null, 'put');
- const del = request.bind(null, 'delete');
- export {
- get,
- post,
- put,
- del as delete,
- };
Advertisement
Add Comment
Please, Sign In to add comment