@wallrio/apimapper v1.0.0
APIMapper
This project aims to facilitate communication with external services via HTTP requests. The idea is to map all external services used in the application and have an internal API Gateway to abstract and centralize the calls.
Installation
npm install @wallrio/apimapper
Configuration
First, the configuration file is created, where endpoints and request parameters are defined.
The configuration file is a JSON file with the following structure:
{
"environment":"prod",
"workspace":{
"id":"id-workspace",
"title":"Title Workspace",
"description":"Description of workspace"
},
"global":{
"headers":{
"Content-Type": "application/json"
},
"vars":{
"author-site":"wallrio.com"
}
},
"vars":{
"prod":{
"accounts": "https://api.{:domain}/accounts",
"travels": "https://api.{:domain}/travels",
"payment": "https://api.{:domain}/payment",
"manager": "https://api.{:domain}/manager"
},
"hmlg":{
"accounts": "http://localhost:8001",
"travels": "http://localhost:8002",
"payment": "http://localhost:8003",
"manager": "http://localhost:8004"
}
},
"requests":{
"accounts/users":{
"method":"get",
"path":"{vars:accounts}/users/{:id}?domain={:domain}",
"headers":{
"custom_header": "{global.vars:author-site}"
},
"description":"this endpoint returns the data of a user",
},
},
"folders":{
"accounts/users":{
"title":"Users",
"parent":"accounts"
},
"accounts":{
"title":"Accounts",
"parent":"/"
}
}
}
Parametro | Descrição | Uso |
---|---|---|
environment | Defines which environment will be used. | Optional |
workspace | Defines which workspace will be used. | Optional |
global | Defines parameters that can be used in all environments. | Optional |
vars | Defines environment-based variables that will be used in endpoints. | Optional |
requests | Defines the endpoints that will be used. | |
folders | Defines categories where requests will be grouped. | Optional |
Minimum parameters the configuration file should have:
{
"requests":{
"accounts/users":{
"method":"get",
"path":"https://api.{:domain}/accounts/users/{:id}?domain={:domain}",
}
}
}
Usage
Initially, two usage modes were envisioned:
- Node
- ContextAPI
Node Mode
In this mode, the library is used individually.
import APIMapper from '@root/lib/APIMapper';
import APIMapperConfig from "@root/../apimapper.routes.json";
// here the configuration file to be used is defined.
const API = new APIMapper(APIMapperConfig);
/*
here the request is made.
the HTTP method parameters are defined in the configuration file.
*/
let responseRequest = await API.request('accounts/users',{
"params":{
"userid":"1234567890"
}
});
Other parameters are allowed:
- params: used for replacing in the endpoint of the request.
- headers: optional, can be defined in the configuration file.
- body: optional.
Example:
let responseRequest = await API.request('accounts/users',{
"params":{
"userid":"1234567890"
},
"headers":{
"Content-Type": "application/json"
}
"body":{
"name":"Fulano da Silva",
"username":"fulano"
}
});
Midleware
It is useful for adding functionality before making the request, and possibly altering some parameters before sending.
If the middleware returns a false promise, the request is aborted.
Example: file @root/src/middleware/APIMapper.middleware.ts
export const middlewareTest = async (path:string, params:Record<string, any>) => {
console.log(path, params,'test...');
params.headers['Content-Type'] = 'application/json';
params.test = 123;
return new Promise((resolve, reject) => {
setTimeout(() => {
// resolve(new Error('Mocked ok')); // the request will be made
reject(new Error('Mocked rejection')); // the request is aborted
}, 5000);
});
}
To add the middleware:
import {middlewareTest} from "@root/src/middleware/APIMapper.middleware"
API.addMiddleware(middlewareTest);
ContextAPI Mode
In this mode, the library is used integrated with a ContextAPI, and the library will be available throughout the application.
Here’s a complete example of how to use it.
Step 1
Create the provider.
- file @root/src/app/context/ProxyProvider.tsx
'use client';
import { createContext} from "react";
export const ProxyContext = createContext({});
import APIMapper from '@root/lib/APIMapper';
import APIMapperConfig from "@root/../APIMapper.routes.json";
export function ProxyProvider({ children }) {
const API = new APIMapper(APIMapperConfig);
return (
<ProxyContext.Provider value={{ authenticated: true,
API:API
}}>
{children}
</ProxyContext.Provider>
);
}
Step 2
Create the application.
- Application
<ProxyProvider>
<Componente>
{children}
</Componente>
</ProxyProvider>
Step 3
Create the component where the HTTP call will be made.
- Component
import { useContext } from "react";
import { ProxyContext } from "./Proxy";
export default function Componente({children}){
const {API} = useContext(ProxyContext);
let responseRequest = await API.request('accounts/users',{
"params":{
"userid":"1234567890"
}
});
}
5 months ago