Skip to content

Instantly share code, notes, and snippets.

@paztek
Created July 18, 2020 15:50
Show Gist options
  • Save paztek/c44df99e2bdf7cc0f7efd983a0c9923c to your computer and use it in GitHub Desktop.
Save paztek/c44df99e2bdf7cc0f7efd983a0c9923c to your computer and use it in GitHub Desktop.
nestjs-http-service-example-1
import { Module } from '@nestjs/common';
import { HttpModule } from './http/http.module';
import { FooModule } from './foo/foo.module';
@Module({
imports: [
HttpModule,
FooModule, // <- we'll make use of the "augmented" HttpService in this module
],
})
export class AppModule {}
import { Controller, Get, HttpService } from '@nestjs/common';
@Controller('/foo')
export class FooController {
constructor(
private readonly httpService: HttpService,
) {}
@Get()
async bar(): Promise<any> {
const response = await this.httpService.get('https://api.github.com/users/paztek').toPromise();
return response.data;
}
}
import { HttpModule, Module } from '@nestjs/common';
import { FooController } from './foo.controller';
@Module({
imports: [
/**
* Here we can import either the common HttpModule or the one we defined.
* It doesn't matter as long as our module is at least imported once (for instance in the AppModule)
*/
HttpModule,
],
controllers: [
FooController,
],
})
export class FooModule {}
import { HttpService, Logger, Module, OnModuleInit, HttpModule as BaseHttpModule } from '@nestjs/common';
@Module({
imports: [
// I prefer temporarily aliasing the homonymous module rather than naming my module MyHttpModule
BaseHttpModule,
],
exports: [
BaseHttpModule,
],
})
export class HttpModule implements OnModuleInit {
constructor(
private readonly httpService: HttpService,
) {}
public onModuleInit(): any {
const logger = new Logger('Axios');
// Add request interceptor and response interceptor to log request infos
const axios = this.httpService.axiosRef;
axios.interceptors.request.use(function (config) {
// Please don't tell my Typescript compiler...
config['metadata'] = { ...config['metadata'], startDate: new Date() };
return config;
});
axios.interceptors.response.use(
(response) => {
const { config } = response;
config['metadata'] = { ...config['metadata'], endDate: new Date() };
const duration = config['metadata'].endDate.getTime() - config['metadata'].startDate.getTime();
// Log some request infos (you can actually extract a lot more if you want: the content type, the content size, etc.)
logger.log(`${config.method.toUpperCase()} ${config.url} ${duration}ms`);
return response;
},
(err) => {
logger.error(err);
// Don't forget this line like I did at first: it makes your failed HTTP requests resolve with "undefined" :-(
return Promise.reject(err);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment