@mondart/nestjs-common-module-request
v3.1.9
Published
HTTP request module and service for NestJS.
Readme
@mondart/nestjs-common-module-request
A small HTTP client wrapper for NestJS: a RequestModule that registers a
global RequestService built on @nestjs/axios, for calling other HTTP
services with a bearer token attached.
Registration
import { RequestModule } from '@mondart/nestjs-common-module-request';
@Module({
imports: [RequestModule],
})
export class AppModule {}RequestModule is @Global(), so RequestService is available for
injection anywhere without re-importing the module.
RequestService
import { RequestService, HttpMethods } from '@mondart/nestjs-common-module-request';
constructor(private readonly requestService: RequestService) {}
const user = await this.requestService.get({
path: 'https://api.example.com/users/1',
token: accessToken,
});
await this.requestService.post({
path: 'https://api.example.com/users',
body: { name: 'Ada' },
token: accessToken,
});
await this.requestService.patch({ path: '...', body: { name: 'Ada L.' } });
await this.requestService.remove({ path: 'https://api.example.com/users/1' });post/get/patch/remove are convenience wrappers around send with
method fixed to the matching HttpMethods value. path is used as the
full request URL, token (if given) is sent as Authorization: Bearer
<token>, and params, if given, is appended to path as-is (e.g.
'foo=1&bar=2') rather than being serialized from an object.
send resolves to result.data on success. On failure it does not
throw — the caught error is returned as the resolved value instead, so
callers must check the result shape rather than relying on a rejected
promise or a try/catch.
const result = await this.requestService.get({ path: '...' });
if (result instanceof Error) {
// handle failure
}sendRaw
sendRaw returns the full Axios response instead of just the body, and
supports resolving path against a configured base URL:
await this.requestService.sendRaw({
method: HttpMethods.GET,
path: '/users/1',
isAdditionalPath: true, // path is appended to config `app.baseUrl`
token: accessToken,
});When isAdditionalPath is true, the request URL is
configService.get('app.baseUrl') + path; otherwise path is used as the
full URL, same as send.
