HTTP Service
Provides
-
useHttpService
-
createApiServiceContainer
-
BaseService
Usage
useHttpService
(config, interceptors)
1. setup
import { useHttpService } from 'http-service';
import {
paramsSerializer,
requestSerializer,
responseSerializer
} from './lib/serializers';
import { right, left } from './lib/monades/either';
const config = {
baseURL: 'https://some-domain.com/api',
paramsSerializer,
transformRequest: [requestSerializer],
transformResponse: [responseSerializer],
};
const interceptors = {
request: [(config) => (config.headers['Accept'] = 'application/json'), undefined]
response: [
[res => right(res), error => left(error)]
],
}
export const {
httpService,
defineService,
setHeader,
setInterceptors
} = useHttpService(config, interceptors);
2. Use dependency injection
export class UserService {
#httpService = null;
constructor(httpService) {
this.#httpService = httpService;
}
get http() {
return this.#httpService;
}
async getUser(params) {
return await this.http.get('/users/1', { params });
}
}
3. or simple
import { httpService } from '../services/http.service.js'
httpService.get('/products', { params: { limit: 10, offset: 20 } });
createApiServiceContainer
(httpConfig, httpInterceptors, serviceList)
httpConfig
and httpInterceptors
contracts equals to useHttpService
arguments.
serviceList
is array of constructors, for example:
import { UserService } from '../services/user.service.js';
import { ProductService } from '../services/product.service.js';
const serviceList = [
UserService,
ProductService
];
and use factory:
import { createApiServiceContainer } from 'http-service';
const config = {
baseURL: 'https//some-domain.com/api'
};
export const container = createApiServiceContainer(serviceList, config)
BaseService
(httpService)
Is class for inheritance and provide to your own classes context http methods and setHeader
method.
http methods provides: get, delete, head, options, post, put, patch
and axios special request
import { BaseService } from 'http-service';
import { httpService } from '../services/http.service.js';
export class TransactionService extends BaseService {
constructor(httpService, some, other, args) {
super(httpService);
}
async getTransactions(params) {
return await this.get('/transactions', { params });
}
async createNewTransaction(payload) {
return await this.post('/transactions', payload);
}
}