Forked from martinobordin/AngularRxJs5DateHttpInterceptor.ts
Last active
January 24, 2019 15:47
-
-
Save bhalash/038b033d125f6948db830f77b3469894 to your computer and use it in GitHub Desktop.
An Angular (> 4.3) interceptor to parse dates from server response.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Recursively walk HttpResponse object to cast ISO 8601-formatted dates as | |
* Moment.js objects. | |
* | |
* @see https://git.io/fNzJw | |
* @see https://www.npmjs.com/package/is-iso-date | |
* @see https://www.npmjs.com/package/traverse | |
*/ | |
import { Injectable } from '@angular/core'; | |
import { Observable } from 'rxjs/Observable'; | |
import 'rxjs/add/operator/do'; | |
import * as moment from 'moment'; | |
import isIsoDate from 'is-iso-date'; | |
import traverse from 'traverse'; | |
import { | |
HttpErrorResponse, | |
HttpEvent, HttpHandler, | |
HttpInterceptor, | |
HttpRequest, | |
HttpResponse | |
} from '@angular/common/http'; | |
@Injectable() | |
export class AngularDateHttpInterceptor implements HttpInterceptor { | |
private static castDateAsMoment(event: HttpEvent<any>): void { | |
if (event instanceof HttpResponse) { | |
traverse(event.body).forEach(function(value: any): void { | |
if (isIsoDate(value)) { | |
this.update(moment(value), true); | |
} | |
}); | |
} | |
} | |
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
return next.handle(req).do(AngularDateHttpInterceptor.castDateAsMoment); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment