Recently, I read an article that inspired me to write this one. That story was about an amazing library that allows you to add a theme switcher into your application with just one line of JavaScript.
Therefore, today I will be sharing with you a repository that I developed some time ago to improve my working skills with the TypeScript language and the famous promises.
So, here we go!
Requests
After some time programming and handling common requests, you've probably seen code like this:
fetch(someUrl)
.then(response => response.json())
.then(response => doSomething(response));
The boring thing about the example above is that we need to parse the response before using it.
The first goal of my package is to make it easier. In the example below, we use RequestParser
to make a request and get its parsed response:
const http = new RequestParser('https://api.example.com');
let usersList = [];
http.request({ url: 'users', method: 'get' })
.then(users => usersList = users);
Okay, getting the response already parsed makes our lives simpler, but the title of this article is "Create a front end service with just one line of code". So, what about it?
Creating a service
Sometimes we need to make model-based requests to the server, with operations such as create, retrieve, update, and delete (CRUD). A pre-built service with all these methods would make our work easier, agree?
const userService = new Service('https://api.example.com/users');
Voilรก! With just one line of code, now we have access to all the methods we need to make the CRUD of the User
model!
// Get all users
userService.get();
// Get an user by its id
userService.getById(1);
// Create a new user
userService.post(userObject);
// Update complete user object
userService.put(1, userObject);
// Update partial user object
userService.patch(1, partialUser);
// Delete a user
userService.delete(1);
Customing your service
You may need some additional methods to make your service more useful.
There is no problem! You can extend the class Service
and create your own methods, using the private method request
to make requests to the server. See an example written in the TypeScript language:
class ProductService extends Service<Product> {
constructor() {
super('https://api.example.com/products');
}
getOffers() {
// GET https://api.example.com/products/offers
return this.request<Product[]>({
url: 'offers',
method: 'get'
});
}
}
Conclusion
The sky's the limit! You can do amazing things with this package. To install it in your project, run:
npm i http-service-ts
The official repository is available here. Feel free to read the docs, use it, fork it, and collaborate on it. And if you like the idea behind this package, may you like the previous article I wrote, where I talk about another npm package I created to make our lives easier.
Thanks for reading - see you in the next article! ๐โ๐ป