web-api
v0.2.0
Published
A generic web API wrapping window.fetch
Downloads
79
Maintainers
Readme
web-api
WARNING: This is an experimental WIP
The purpose of this library is to abstract the usage of window.fetch
in a more involved environment, where pre and post transformations are made. It's an initial attempt at generalizing some concepts, so that request processing code can be shared across projects. Hopefully this will make creating an API interfaces is quicker and easier.
I envision this being a project where people can discuss various approaches and contribute to building a solid best practices guide for handling the request part of getting data. (Redux already manages the handling of the data well, but doesn't give much guidance on how to request the data).
Getting started
Although it isn't necessary, creating a base class for a kind of API (this example is using the Json placeholder API), helps to keep global API variables and functionality at that level.
Create a base API class which extends BaseWebAPI
.
PlaceholderAPI.js
import { BaseWebAPI } from 'web-api';
class PlaceholderAPI extends BaseWebAPI {
constructor(options = {}) {
const urlSchema = 'http'; // The default protocol used in BaseWebAPI is https
const hostURL = 'jsonplaceholder.typicode.com'
const customOptions = {
...options
host: hostURL,
protocol: urlSchema
}; // Use Object.assign to extend any passed in options with our own custom options
super(customOptions);
}
}
export default PlaceholderAPI;
Next we will create a class that groups together all endpoints related to posts
. This can be any arbitrary grouping, but colocating endpoints that pertain to the same resource makes intuitive sense, when using a REST API. This is the point at which a developer defines the interface between the front end and the back end API service. The font end need not mimic the structure of the back end.
PostsAPI.js
import { BaseWebAPI } from 'web-api';
import { createAPI } from 'web-api';
class PostsAPI extends BaseWebAPI {
constructor(options) {
super(options);
}
async getAllPosts() {
return await this.get('/posts') // `this.get` creates a GET request to the resource and appends the url `/posts` to `http://jsonplaceholder.typicode.com`.
}
}
export default createAPI(PostsAPI);
We can then reference this in the rest of our code to get the processed response.
somefile.js
import { PostsAPI } from PostsAPI;
const allPosts = PostsAPI.getAllPosts();
Basic concepts
- Create a declarative API on which transformations of a request and a response can be defined.
- Transformations are applied in sequence and can be defined globally, or for a specific request.