Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. //timeout.interceptor.ts
  2.  
  3. import { Injectable, NestInterceptor, CallHandler, HttpCode } from '@nestjs/common';
  4. import { Observable } from 'rxjs';
  5. import Axios from 'axios';
  6.  
  7.  
  8. @Injectable()
  9. export class TimeoutInterceptor implements NestInterceptor {
  10. intercept(context: any, next: CallHandler): Observable<any> {
  11.  
  12. const CancelToken = Axios.CancelToken;
  13. const source = CancelToken.source();
  14.  
  15. const url: string = context.url ? context.url : context.args[0].url;
  16. Axios.defaults.timeout = 200;
  17.  
  18.  
  19. Axios.get(url, {
  20. cancelToken: source.token
  21. }).then((res) => {
  22. }, error => {
  23. if (error.message.indexOf('timeout') >= 0) {
  24. throw new Axios.Cancel('Operation canceled due to timeout!');
  25. }
  26. }
  27. ).catch((error) => {
  28. if (Axios.isCancel(error)) {
  29. console.log('Request canceled ', error);
  30. } else {
  31. console.log('--else part--');
  32. }
  33. });
  34. return next.handle();
  35. }
  36. }
  37.  
  38. // timeout.interceptor.spec.ts
  39.  
  40. import { Test, TestingModule } from '@nestjs/testing';
  41. import {
  42. HttpModule, Controller,
  43. ExecutionContext,
  44. Get,
  45. InternalServerErrorException
  46. } from '@nestjs/common';
  47. import { of, Observable, throwError } from 'rxjs';
  48. //import { Reflector } from '@nestjs/core';
  49. import Axios from 'axios';
  50.  
  51. describe('Content Service', () => {
  52. let module: TestingModule;
  53. //let reflector;
  54. let timeoutInterceptor;
  55. //const loggerSpy = jest.fn()
  56. let getSpy;
  57. let cancelSpy;
  58. const errCode = 'MockController#decorated';
  59. const errMessage = 'Controller threw an error';
  60.  
  61.  
  62. beforeEach(async () => {
  63. module = await Test.createTestingModule({
  64. imports: [HttpModule],
  65.  
  66. }).compile();
  67.  
  68. getSpy = jest.spyOn(Axios, 'get');
  69. timeoutInterceptor = new timeoutInterceptor();
  70. })
  71.  
  72. it('should call Axios.Cancel when it catches an timeout>0', done => {
  73.  
  74. const context={url:''}
  75. timeoutInterceptor.intercept(context, throwError(new InternalServerErrorException()))
  76. .subscribe(
  77. () => { },
  78. () => {
  79. expect(Axios.Cancel).toHaveBeenCalled();
  80. done();
  81. }
  82. )
  83. .unsubscribe();
  84. });
  85.  
  86. })
  87.  
  88. ;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement