routit is a tool for using your API easily in your project. It has an easy setup and implementation that will save your time.
To install, run:
> npm install routitFor using routit in your project, you must have it imported.
import { RestRoute, RoutitServer } from 'routit'We are assuming that you have a API server in https://api.myserver.com and it have an API route /todos. Let's look at how we can implement this
First of all, you need to create a class that inherits from RoutitServer and add serverRoot property on it. serverRoot is the root URL of your server. Note: Do not add a slash at the end of URL.
class MyServer extends RoutitServer {
serverRoot = 'https://api.myserver.com'
}The name of the class can be whatever you want.
You can create routes using the RestRoute class. It accepts two parameters:
server-RoutitServerobject to set host server of the route. You can pass the object by passingthisin class.routeName-stringfor setting which route API call has to be done. In our example, it must betodos. Note: Do not add a slash at the end ofrouteName.
class MyServer extends RoutitServer {
serverRoot = 'https://api.myserver.com'
Todos = new RestRoute(this, 'todos')
}The last thing to use your api in your project is to create an object of the server.
const API = new MyServer()There 2 ways of get request. One is getAll, other is getOne.
getAll is used for fetch all the elements.
var response = await API.Todos.getAll()
// This will request https://api.myserver.com/todos with GETgetOne is used for fetch one element by id.
var response = await API.Todos.getOne(5)
// This will request https://api.myserver.com/todos/5 with GETpost method will send data to server. (Mostly for creating)
var response = await API.Todos.post({
id: 15,
completed: false,
title: 'lorem lorem',
userId: 1,
})
// This will request https://api.myserver.com/todos with POSTput method will send data to server by id. (Mostly for replacing data)
var response = await API.Todos.put(15, {
userId: 1,
title: 'lorem ipsum',
completed: true,
})
// This will request https://api.myserver.com/todos/15 with PUTpatch method will send data to server by id. (Mostly for patching data)
var response = await API.Todos.patch(15, {
title: 'lorem ipsum dolor',
})
// This will request https://api.myserver.com/todos/15 with PATCHdelete method will send delete request to server by id.
var response = await API.Todos.delete(15)
// This will request https://api.myserver.com/todos/15 with DELETE