1 | import {Fields} from '@loopback/filter';
|
2 | import {cloneDeep} from 'lodash';
|
3 |
|
4 | export function includeFieldIfNot<MT>(
|
5 | fields: Fields<MT> | undefined,
|
6 | fieldToInclude: Extract<keyof MT, string>,
|
7 | ): false | Fields<MT> {
|
8 | if (!fields) {
|
9 | return false;
|
10 | } else if (Array.isArray(fields)) {
|
11 | const fieldsCloned: {[P in keyof MT]?: boolean} = fields.reduce(
|
12 | (prev, current) => ({...prev, [current]: true}),
|
13 | {},
|
14 | );
|
15 | if (Object.keys(fieldsCloned).length > 0) {
|
16 | if (fieldsCloned[fieldToInclude] === true) {
|
17 | return false;
|
18 | }
|
19 | fieldsCloned[fieldToInclude] = true;
|
20 | return fieldsCloned;
|
21 | }
|
22 | return false;
|
23 | }
|
24 |
|
25 | const fieldsCloned = cloneDeep(fields);
|
26 | if (Object.keys(fieldsCloned).length > 0) {
|
27 | let containsTrue = false;
|
28 | for (const k in fieldsCloned) {
|
29 | if (fieldsCloned[k] === true) {
|
30 | containsTrue = true;
|
31 | }
|
32 | }
|
33 | for (const k in fieldsCloned) {
|
34 | if (k === fieldToInclude) {
|
35 | if (fieldsCloned[k] === true) {
|
36 | return false;
|
37 | } else {
|
38 | if (containsTrue) {
|
39 | fieldsCloned[k] = true;
|
40 | } else {
|
41 | delete fieldsCloned[k];
|
42 | }
|
43 | return fieldsCloned;
|
44 | }
|
45 | }
|
46 | }
|
47 | if (containsTrue) {
|
48 | fieldsCloned[fieldToInclude] = true;
|
49 | return fieldsCloned;
|
50 | } else {
|
51 | return false;
|
52 | }
|
53 | } else {
|
54 | return false;
|
55 | }
|
56 | }
|