1 /**
2 * Transform a remote query object to a string array containing the chain of fields and relations
3 *
4 * @param fields
5 * @param parent
6 *
7 * @example
8 *
9 * const remoteQueryObject = {
10 * fields: [
11 * "id",
12 * "title",
13 * ],
14 * images: {
15 * fields: ["id", "created_at", "updated_at", "deleted_at", "url", "metadata"],
16 * },
17 * }
18 *
19 * const fields = remoteQueryObjectToString(remoteQueryObject)
20 *
21 * console.log(fields)
22 * // ["id", "title", "images.id", "images.created_at", "images.updated_at", "images.deleted_at", "images.url", "images.metadata"]
23 */
24 export function remoteQueryObjectToString(
25 fields: object,
26 parent?: string
27 ): string[] {
28 return Object.keys(fields).reduce((acc, key) => {
29 if (key === "fields") {
30 if (parent) {
31 fields[key].map((fieldKey) => acc.push(`${parent}.${fieldKey}`))
32 } else {
33 fields[key].map((fieldKey) => acc.push(fieldKey))
34 }
35
36 return acc
37 }
38
39 if (typeof fields[key] === "object") {
40 acc = acc.concat(
41 remoteQueryObjectToString(
42 fields[key],
43 parent ? `${parent}.${key}` : key
44 )
45 )
46 return acc
47 }
48
49 return acc
50 }, [] as string[])
51 }