Created
May 7, 2020 12:18
-
-
Save fedotxxl/7ef8650a40abe7bc69425df448c18bca to your computer and use it in GitHub Desktop.
This file contains 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
import {Injectable} from '@angular/core'; | |
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http'; | |
import {Observable} from "rxjs"; | |
import {map} from "rxjs/operators"; | |
@Injectable() | |
export class DateHttpInterceptor implements HttpInterceptor { | |
// Migrated from AngularJS https://raw.githubusercontent.com/Ins87/angular-date-interceptor/master/src/angular-date-interceptor.js | |
private static iso8601Date = /^\d{4}-\d\d-\d\d?$/; | |
private static iso8601DateTime = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/; | |
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
return next.handle(req).pipe( | |
map(e => { | |
if (e instanceof HttpResponse) { | |
const body = e.body; | |
this.convertToDate(body); | |
} | |
return e; | |
}) | |
); | |
} | |
convertToDate(body) { | |
if (body === null || body === undefined) { | |
return body; | |
} | |
if (typeof body !== 'object') { | |
return body; | |
} | |
for (const key of Object.keys(body)) { | |
const value = body[key]; | |
if (this.isIso8601(value)) { | |
body[key] = new Date(value); | |
} else if (typeof value === 'object') { | |
this.convertToDate(value); | |
} | |
} | |
} | |
isIso8601(value) { | |
if (value === null || value === undefined) { | |
return false; | |
} | |
return DateHttpInterceptor.iso8601Date.test(value) || DateHttpInterceptor.iso8601DateTime.test(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment