Last active
October 25, 2020 13:37
-
-
Save abdelgrib/b644cd149624fe4da6d0154e747dd19a to your computer and use it in GitHub Desktop.
JavaScript - HTTP and Fetch API helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const Status = { | |
Ok: 200, | |
Unassigned: 299, | |
BadRequest: 400, | |
Unauthorized: 401, | |
NotFound: 404, | |
}; | |
export const Methods = { | |
Get: "GET", | |
Post: "POST", | |
Put: "PUT", | |
Delete: "DELETE", | |
}; | |
export const Headers = { | |
Accept: "application/json", | |
"Content-Type": "application/json", | |
}; | |
export const AuthorizationType = { | |
Bearer: "bearer ", | |
Basic: "basic " | |
} | |
export const Credentials = { | |
SameOrigin: "same-origin", /* default */ | |
Include: "include", | |
Omit: "omit" | |
} | |
export const addAuthorization = (headers, type, value) => { | |
headers["Authorization"] = `${type}${value}`; | |
} | |
class HttpHelper { | |
static post = (url, body) => { | |
return fetch(url, { | |
method: Methods.Post, | |
/*credentials: Credentials.Include,*/ | |
headers: Headers, | |
body: JSON.stringify(body), | |
}) | |
.then(this.handleResponse) | |
.catch(this.handleUnexpectedError); | |
}; | |
static get = (url, query) => { | |
if (query) | |
url += "?" + new URLSearchParams(query).toString(); | |
return fetch(url, { | |
method: Methods.Get, | |
/*credentials: Credentials.Include,*/ | |
headers: Headers | |
}) | |
.then(this.handleResponse) | |
.catch(this.handleUnexpectedError); | |
}; | |
static handleResponse = (response) => { | |
const headers = this.readHeaders(response.headers); | |
if (this.isError(response)) | |
return this.handleExpectedError(response, headers); | |
return response.json().then((body) => { | |
return new AppResponse(body, headers); | |
}); | |
/*In case of issue with empty responses use .text() instead of .json()*/ | |
/*Same thing to do for handleExpectedError*/ | |
// return response.text().then((bodyText) => { | |
// let body = bodyText ? JSON.parse(bodyText) : {}; | |
// return new AppResponse(body, headers); | |
// }); | |
}; | |
static handleExpectedError = (error, headers) => { | |
/*Expected (Unhandled exceptions if treated to 500)*/ | |
/*See : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch*/ | |
return error.json().then((body) => { | |
switch (error.status) { | |
case Status.BadRequest: | |
return Promise.reject(new BadRequestError(body, headers)); | |
case Status.Unauthorized: | |
return Promise.reject(new UnauthorizedError(body, headers)); | |
case Status.NotFound: | |
return Promise.reject(new NotFoundError(body, headers)); | |
default: | |
return Promise.reject(new AppError(body, headers)); | |
} | |
}); | |
}; | |
static handleUnexpectedError = (error) => { | |
/*Unexpected: Server offline, Network down, Unhandled exceptions*/ | |
/*return need to be rejected again*/ | |
if (!(error instanceof AppError)) | |
return Promise.reject(new AppError(error)); | |
/*handleExpectedError return will get here*/ | |
return Promise.reject(error); | |
}; | |
static isError = (response) => { | |
return response.status < Status.Ok || response.status > Status.Unassigned; | |
}; | |
static readHeaders = (headers) => { | |
let headersObject = {}; | |
headers.forEach((value, key) => { | |
headersObject[key] = value; | |
}); | |
return headersObject; | |
}; | |
} | |
export default HttpHelper; | |
export class AppResponse { | |
constructor(body = null, headers = null) { | |
this.body = body; | |
this.headers = headers; | |
} | |
} | |
export class AppError { | |
constructor(body = null, headers = null) { | |
this.body = body; | |
this.headers = headers; | |
} | |
} | |
export class NotFoundError extends AppError { | |
constructor(body = null, headers = null) { | |
super(body, headers); | |
} | |
} | |
export class BadRequestError extends AppError { | |
constructor(body = null, headers = null) { | |
super(body, headers); | |
} | |
} | |
export class UnauthorizedError extends AppError { | |
constructor(body = null, headers = null) { | |
super(body, headers); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment