Basic usage
example
const client = new HttpClient();
const data = await client.get('https://my-api.com/data').json();
Basic request
example
const client = new HttpClient();
const request = {
id: 1,
name: 'test'
};
await client.post('https://my-api.com/data', { json: request }).execute();
Usage with di
example
@injectable()
class MyClass {
constructor(@inject(IHttpClient$) private readonly _client: IHttpClient) {}
}
Basic intercepting
example
// myApiInterceptor.ts
@extension({ name: 'MyApiInterceptor' })
export class MyApiInterceptor extends HttpInterceptor<ApiClientOptions> {
override async enhanceOptions(
context: HttpInterceptorOptionsContext<ApiClientOptions>
): Promise<void> {
const { options } = context;
options.baseURL = 'https://my-api.com';
}
}
// registrator.ts
extensionContainer.registerExtension({
extension: MyApiInterceptor,
when: whenClientTypeIs(IApiClient$)
});
Usage with hooks
example
const data = await client
.get('https://my-api.com/data', {
hooks: [
{
beforeRequest: async ctx => {
ctx.request.headers.set('my-header', 'my-header-value');
}
}
]
})
.typedJson();
Usage with hooks context
example
const context = new HttpHooksContext([
{
beforeRequest: async ctx => {
ctx.request.headers.set('my-header', 'my-header-value');
}
}
]);
await HttpHooksContext.create(context).run(async () => await someLogicWithHttpRequestInside());
Provide hooks with registration
example
container
.bind(IHttpInterceptorHooksProvider$)
.toFunction(() => [
{
beforeRequest: async ctx => {
ctx.request.headers.set('my-header', 'my-header-value');
}
}
])
.whenAnyAncestorIs(IOperationService$);
Cancellation with context
example
const context = new CancellationContext();
CancellationContext.create(context).run(() => await someLogicWithHttpRequestInside());
context.cancel();