|
1 | | -import { ShowMessage } from './types'; |
| 1 | +import { isArray, isObject, has as $has, first as $first, each as $each } from 'lodash'; |
2 | 2 |
|
3 | | -export const showMessage: ShowMessage = (message) => console.log(message); |
| 3 | +/** |
| 4 | + * Transform the Strapi API response removing the not needed nesting |
| 5 | + * @param data object to mapping |
| 6 | + * @returns mapped object |
| 7 | + */ |
4 | 8 |
|
5 | | -showMessage('Hello world!'); |
| 9 | +export function mapperData<T>(data: any): T { |
| 10 | + // Single |
| 11 | + if ($has(data, 'attributes')) { |
| 12 | + return mapperData(removeObjectKey(data, 'attributes')); |
| 13 | + } |
| 14 | + |
| 15 | + // collection |
| 16 | + if (isArray(data) && data.length && $has($first(data), 'attributes')) { |
| 17 | + return data.map((el: any) => mapperData(el)) as T; |
| 18 | + } |
| 19 | + |
| 20 | + // Fields |
| 21 | + $each(data, (value, key) => { |
| 22 | + if (!value) return; |
| 23 | + |
| 24 | + // single |
| 25 | + if (isObject(value)) { |
| 26 | + data[key] = mapperData(value); |
| 27 | + } |
| 28 | + |
| 29 | + // many |
| 30 | + if (isArray(value)) { |
| 31 | + data[key] = value.map((field) => mapperData(field)); |
| 32 | + } |
| 33 | + |
| 34 | + // relation(s) |
| 35 | + if ($has(value, 'data')) { |
| 36 | + let relation = null; |
| 37 | + |
| 38 | + // single |
| 39 | + if (isObject(value.data)) { |
| 40 | + relation = mapperData(value.data); |
| 41 | + } |
| 42 | + |
| 43 | + // many |
| 44 | + if (isArray(value.data)) { |
| 45 | + relation = value.data.map((el: any) => mapperData(el)); |
| 46 | + } |
| 47 | + |
| 48 | + data[key] = relation; |
| 49 | + } |
| 50 | + |
| 51 | + // single component |
| 52 | + if ($has(value, 'id')) { |
| 53 | + data[key] = mapperData(value); |
| 54 | + } |
| 55 | + |
| 56 | + // repeatable component & dynamic zone |
| 57 | + if (isArray(value) && $has($first(value), 'id')) { |
| 58 | + data[key] = value.map((p) => mapperData(p)); |
| 59 | + } |
| 60 | + |
| 61 | + // single media |
| 62 | + if ($has(value, 'provider')) { |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + // multiple media |
| 67 | + if (isArray(value) && $has($first(value), 'provider')) { |
| 68 | + return; |
| 69 | + } |
| 70 | + }); |
| 71 | + |
| 72 | + return data; |
| 73 | +} |
| 74 | + |
| 75 | +const removeObjectKey = <T extends { [key: string]: any }>(object: T, key: string): T => ({ |
| 76 | + id: object.id, |
| 77 | + ...object[key], |
| 78 | +}); |
0 commit comments