Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export default new class {
- constructor() {
- this.apiPrefix = `/api`;
- this.apiPrefix = `https://medwise.webstaginghub.com//api`;
- }
- defaultHeaders() {
- return {
- 'Content-Type': 'application/json',
- };
- }
- authTokenHeaders(headers = {}) {
- return {
- ...(headers || {}),
- Authorization: localStorage.getItem('authToken')
- };
- }
- async handleUnauthorize(result) {
- const json = await result.json();
- if (!json.success && json.message === 'Invalid token') {
- location.reload();
- await new Promise(resolve => setTimeout(resolve, 1000));
- }
- return json;
- }
- get(url, headers = false, options = {}) {
- if (!headers) headers = this.defaultHeaders();
- headers = this.authTokenHeaders(headers);
- const prefix = options.hasOwnProperty('prefix') ? options.prefix : this.apiPrefix;
- return fetch(`${prefix}/${url}`, { headers }).then(res => {
- if (res.status === 403) setTimeout(() => location.reload(), 500);
- return this.handleUnauthorize(res);
- });
- }
- delete(url, headers = false) {
- if (!headers) headers = this.defaultHeaders();
- headers = this.authTokenHeaders(headers);
- return fetch(`${this.apiPrefix}/${url}`, {
- method: 'DELETE', headers
- }).then(res => this.handleUnauthorize(res));
- }
- post(url, data = {}, headers = false) {
- if (!headers) headers = this.defaultHeaders();
- headers = this.authTokenHeaders(headers);
- return fetch(`${this.apiPrefix}/${url}`, {
- method: 'post', body: data, headers
- }).then(res => this.handleUnauthorize(res));
- }
- put(url, data = {}, headers = false) {
- if (!headers) headers = this.defaultHeaders();
- headers = this.authTokenHeaders(headers);
- return fetch(`${this.apiPrefix}/${url}`, {
- method: 'put', body: data, headers
- }).then(res => this.handleUnauthorize(res));
- }
- jsonToFormData(obj, form = new FormData(), namespace = '') {
- for (let key in obj) {
- if (obj.hasOwnProperty(key)) {
- let formKey = namespace ? `${namespace}[${key}]` : key;
- if (obj[key] instanceof File) {
- form.append(formKey, obj[key]);
- } else if (obj[key] instanceof Array) {
- obj[key].forEach((item, index) => {
- this.jsonToFormData(item, form, `${formKey}[${index}]`);
- });
- } else if (typeof obj[key] === 'object' && obj[key] !== null) {
- this.jsonToFormData(obj[key], form, formKey);
- } else {
- form.append(formKey, obj[key]);
- }
- }
- }
- return form;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement