Files
medusa-store/packages/modules/index/src/utils/flatten-object-keys.ts
Adrien de Peretti 3084008fc9 feat(index): Provide a similar API to Query (#9193)
**What**
Align the index engine API to be similar to the Query API

## Example

```ts
        // Benefit from the same level of typing like the remote query

        const { data, metadata } = await indexEngine.query<'product'>({
          fields: [
            "product.*",
            "product.variants.*",
            "product.variants.prices.*",
          ],
          filters: {
            product: {
              variants: {
                prices: {
                  amount: { $gt: 50 },
                },
              },
            },
          },
          pagination: {
            order: {
              product: {
                variants: {
                  prices: {
                    amount: "DESC",
                  },
                },
              },
            },
          },
        })
```
2024-09-20 10:02:42 +00:00

60 lines
1.0 KiB
TypeScript

import { OPERATOR_MAP } from "./query-builder"
/**
* Flatten object keys
* @example
* input: {
* a: 1,
* b: {
* c: 2,
* d: 3,
* },
* e: 4,
* }
*
* output: {
* a: 1,
* b.c: 2,
* b.d: 3,
* e: 4,
* }
*
* @param input
*/
export function flattenObjectKeys(input: Record<string, any>) {
const result: Record<string, any> = {}
function flatten(obj: Record<string, any>, path?: string) {
for (const key in obj) {
const isOperatorMap = !!OPERATOR_MAP[key]
if (isOperatorMap) {
result[path ?? key] = obj
continue
}
const newPath = path ? `${path}.${key}` : key
if (obj[key] === null) {
result[newPath] = null
continue
}
if (Array.isArray(obj[key])) {
result[newPath] = obj[key]
continue
}
if (typeof obj[key] === "object" && !isOperatorMap) {
flatten(obj[key], newPath)
continue
}
result[newPath] = obj[key]
}
}
flatten(input)
return result
}