Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 58 59 60 61 62 63 64 65 66 | 1x 1x 1x 1x 1x 143x | import { InvocationContext, InvocationResult, ValueOrPromise, } from '@loopback/core';
import { RestBindings } from '@loopback/rest';
import { SecurityBindings } from '@loopback/security';
import { ClassConstructor, instanceToPlain } from 'class-transformer';
import { isObject } from 'lodash';
import { BaseResponses } from '@logchain/models';
import { AnyObject } from '@logchain/types';
/**
* The intercept to serialize data before return.
* @param cls The DTO Class
*/
export function serialize<T>(cls: ClassConstructor<T>) {
return async (
invocationCtx: InvocationContext,
next: () => ValueOrPromise<InvocationResult>,
) => {
let result = await next();
if (!isObject(result)) {
return result;
}
result = result as BaseResponses<T>;
const [httpReq, currentUser] = await Promise.all([
invocationCtx.get(RestBindings.Http.REQUEST, {
optional: true,
}),
invocationCtx.get(SecurityBindings.USER, {
optional: true,
})
]);
// Add pre-invocation logic here
const groups: string[] = [currentUser?.timezone];
if (httpReq?.url.startsWith('/admin')) {
groups.push('private');
} else {
groups.push('public');
}
const hasData = !!result.data;
if (!hasData) {
groups.push('single');
let identifier;
if (Object.hasOwnProperty.call(result, 'identifier')) {
identifier = result.identifier;
}
const resl = instanceToPlain(new cls(result), { groups });
if (identifier) {
resl.identifier = identifier;
}
delete resl.user_timezone;
return resl;
}
groups.push('list');
result.data = instanceToPlain(
result.data.map((ele: AnyObject) => {
return new cls(ele);
}),
{ groups },
);
return result;
};
}
|