-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathresponse.interceptor.ts
More file actions
57 lines (48 loc) · 1.7 KB
/
response.interceptor.ts
File metadata and controls
57 lines (48 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { instanceToPlain } from 'class-transformer';
import { isArray, isObject } from 'lodash';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Response<T> {
data: T;
}
@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context, next: CallHandler): Observable<Response<T>> {
if ((context.getType() as string) === 'graphql') return next.handle();
return next.handle().pipe(
map((data) => {
if (this.returnWholeObject(data)) {
return {
...data,
data: isObject(data.data) ? this.transformResponse(data.data) : data.data,
};
}
return {
data: isObject(data) ? this.transformResponse(data) : data,
};
})
);
}
/**
* This method is used to determine if the entire object should be returned or just the data property
* for paginated results that already contain the data wrapper, true.
* for single entity result that *could* contain data object, false.
* @param data
* @private
*/
private returnWholeObject(data) {
const isPaginatedResult = data?.data;
const isEntityObject = data?._id || data?.id;
return isPaginatedResult && !isEntityObject;
}
private transformResponse(response) {
if (isArray(response)) {
return response.map((item) => this.transformToPlain(item));
}
return this.transformToPlain(response);
}
private transformToPlain(plainOrClass) {
return plainOrClass && plainOrClass.constructor !== Object ? instanceToPlain(plainOrClass) : plainOrClass;
}
}