Fetch ES6 Class

Ernesto Jara Olveda
2 min readJan 4, 2021

If you do not need to support them ugly browsers out there. IE you know we are talking about you. npm package and git repo will be at the end. lets start.

Let’s start by defining the methods that our class will have:

Methods

request

A method in which you can customise the request

uploadFile

This method will send a file to backend.

cacheFirst

We first check if this url is already fetched if so, we just return it, else we trigger the HTTP request then we cached the result if it doesn't have an error.

GET

The HTTP GET method requests a representation of the specified resource. Requests using GET should only be used to request data they shouldn’t include data.

Post

The HTTP POST method sends data to the server. The type of the body of the request is indicated by the `Content-Type` header.

The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect that is no side effect, where successive identical POST may have additional effects, like passing an order several times.

Delete

The HTTP DELETE request method deletes the specified resource.

Put

The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.

Patch

The HTTP PATCH request method applies partial modifications to a resource.

PATCH is somewhat analogous to the update concept found in `CRUD` (in general, HTTP is different than `CRUD`, and the two should not be confused).

A PATCH request is considered a set of instructions on how to modify a resource. Contrast this with PUT; which is a complete representation of a resource. A PATCH is not necessarily idempotent, although it can be. Contrast this with PUT; which is always idempotent. The word idempotent means that any number of repeated, identical requests will leave the resource in the same state.

For example if an auto-incrementing counter field is an integral part of the resource, then a PUT will naturally overwrite it (since it overwrites everything), but not necessarily so for PATCH. PATCH (like POST) may have side-effects on other resources.

So far our class looks like this:

class Fetch {public request();
public uploadFile();
public cacheFirst();
public get();
public post();
public put();
public delete();
public patch();
}export default Fetch;

There once you copy the class the way to implement it is very easy. let’s create the user class

class UserApi extends Fetch {  public login (username:string, password: string) {
return this.post("https://www.url.com/api/login", {username,password})
}
}

--

--