Skip to content

Instantly share code, notes, and snippets.

@josuesilva-hotmart
Created April 22, 2019 15:44
Show Gist options
  • Save josuesilva-hotmart/5a323c69de1d0908789edcf33d23e21b to your computer and use it in GitHub Desktop.
Save josuesilva-hotmart/5a323c69de1d0908789edcf33d23e21b to your computer and use it in GitHub Desktop.

Revisions

  1. josuesilva-hotmart created this gist Apr 22, 2019.
    79 changes: 79 additions & 0 deletions base-service.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,79 @@
    export default class BaseService {
    defaultHeaders: DefaultHeaders;

    constructor(token: string) {
    this.defaultHeaders = {
    Authorization: `Bearer ${token}`,
    Accept: "application/json",
    "Content-Type": "application/json"
    };
    }

    get(path: string) {
    return fetch(`${API_URL}${path}`, { headers: this.defaultHeaders })
    .then(this.checkUnauthorized)
    .then(response => {
    return response.json();
    });
    }

    post(path: string, form: Object) {
    return fetch(`${API_URL}${path}`, this.body(POST_METHOD, form))
    .then(this.checkStatus)
    .then(response => {
    if (
    path.includes("accept") ||
    path.includes("conclude") ||
    path.includes("cancel") ||
    path.includes("signup")
    ) {
    return response.text();
    }

    return response.json();
    });
    }

    put(path: string, form: Object) {
    return fetch(`${API_URL}${path}`, this.body(PUT_METHOD, form))
    .then(this.checkStatus)
    .then(response => {
    return response.json();
    });
    }

    del(path: string, form: Object) {
    return fetch(`${API_URL}${path}`, this.body(DELETE_METHOD, form))
    .then(this.checkStatus)
    .then(response => {
    return response.json();
    });
    }

    body(method: string, form: Object) {
    return {
    method,
    headers: this.defaultHeaders,
    body: JSON.stringify(form)
    };
    }

    checkUnauthorized = (response: Object) => {
    if (response.status === 401) {
    throw new Error(response.status);
    } else {
    return response;
    }
    };

    checkStatus = (response: Object) => {
    if (response.status >= 200 && response.status < 300) {
    return response;
    } else {
    console.log(response);
    let error: Object = new Error(response.status);
    error.response = response.json();
    throw error;
    }
    };
    }