Dodicifit
Description
A simple wrapper to use with your next application.
Usage
Normally install the package:
[sudo] npm i --save dodicifit
Then you can call the base abstract class to implement a service like this:
import { BaseService } from 'dodicifit'; class ApiService extends BaseService { async getHealthcheck() { const response = await this.makeRequest({ method: 'GET', path: '/', headers: { 'Content-Type': 'application/json', }, }); if (response.statusCode !== 200) { throw new Error(`Failed to fetch healthcheck. Status code: ${response.statusCode}`); } return response.data; } }
And done, now you have a basic implementation of your call who can be called from your source of truthy, simple as like this:
const apiService = new ApiService('http://localhost:3000'); console.log(apiService.getHealthcheck());
Examples
You can use an example of service, to retrieve content from https://random-data-api.com, getting a random user
like this:
npm run example -- .\examples\random-user-service.js
Or just copy and paste with dodicifit installed:
import { BaseService } from 'dodicifit'; class RandomUserService extends BaseService { async getRandomUser() { const response = await this.makeRequest({ method: 'GET', path: '/api/users/random_user', headers: { 'Content-Type': 'application/json', }, }); if (response.statusCode !== 200) { throw new Error(`Failed to fetch random user. Status code: ${response.statusCode}`); } return response.data; } } (async () => { const randomUserService = new RandomUserService('https://random-data-api.com'); const user = await randomUserService.getRandomUser(); console.log(user); })();
Using axios adapter for undici
import axios, { AxiosAdapter } from 'axios'; import { undiciAdapter } from 'dodicifit'; interface Beer { id: number; uid: string; brand: string; name: string; style: string; hop: string; yeast: string; malts: string; ibu: string; alcohol: string; blg: string; } const api = axios.create({ baseURL: 'https://random-data-api.com', adapter: undiciAdapter as AxiosAdapter, headers: { 'Content-Type': 'application/json', } }); interface GetBeerResponse { data: Beer; } const getBeer = async (): Promise<GetBeerResponse> => { const response = await api.get<GetBeerResponse>(`api/v2/beers`); return response.data; }; (async function () { const beer = await getBeer(); console.log(beer); })();
Contributions
Feel free to interact with this project opening PR's and/or suggesting improvements.
Author
Kaique da Silva kaeyosthaeron@gmail.com