Liliana797979

api -js aplications

Dec 4th, 2021
716
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {clearUserData, getUserData, setUserData} from "../util.js";
  2.  
  3. const hostname = 'http://localhost:3030';
  4.  
  5. async function request(url, options) {
  6.     try {
  7.         const response = await fetch(hostname + url, options);
  8.  
  9.         if (response.ok === false) {
  10.             const error = await response.json();
  11.             throw new Error(error.message);
  12.         }
  13.  
  14.         if (response.status === 204) {
  15.             return response;
  16.         } else {
  17.             return response.json();
  18.         }
  19.  
  20.     } catch (err) {
  21.         alert(err.message);
  22.         throw err;
  23.     }
  24. }
  25.  
  26. function createOptions(method = 'get', data) {
  27.     const options = {
  28.         method,
  29.         headers: {}
  30.     };
  31.  
  32.     if (data !== undefined) {
  33.         options.headers['Content-Type'] = 'application/json';
  34.         options.body = JSON.stringify(data);
  35.     }
  36.  
  37.     const userData = getUserData();
  38.     if (userData) {
  39.         options.headers['X-Authorization'] = userData.token;
  40.     }
  41.  
  42.     return options;
  43. }
  44.  
  45. export async function get(url) {
  46.     return request(url, createOptions());
  47. }
  48.  
  49. export function post(url, data) {
  50.     return request(url, createOptions('post', data));
  51. }
  52.  
  53. export function put(url, data) {
  54.     return request(url, createOptions('put', data));
  55. }
  56.  
  57. export function del(url) {
  58.     return request(url, createOptions('delete'));
  59. }
  60.  
  61. export async function login(email, password) {
  62.     const result = await post('/users/login', {email, password});
  63.  
  64.     const userData = {
  65.         email: result.email,
  66.         id: result._id,
  67.         token: result.accessToken
  68.     };
  69.  
  70.     setUserData(userData);
  71.  
  72.     return result;
  73. }
  74.  
  75. export async function register(email, password) {
  76.     const result = await post('/users/register', {email, password});
  77.  
  78.     const userData = {
  79.         email: result.email,
  80.         id: result._id,
  81.         token: result.accessToken
  82.     };
  83.  
  84.     setUserData(userData);
  85.  
  86.     return result;
  87. }
  88.  
  89. export async function logout() {
  90.     get('/users/logout');
  91.     clearUserData();
  92. }
RAW Paste Data