fix(medusa): Clean response data usage for admin and store fields/expand (#3323)

* fix(medusa): Clean response data usage for admin and store fields/expand

* cleanup

* Create mighty-ads-fold.md

* fix integration

* fix integration

* refactor transform query and cleanup

* fix missing re naming

* Update packages/medusa/src/api/middlewares/transform-query.ts

---------

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
Adrien de Peretti
2023-02-28 09:48:08 +01:00
committed by GitHub
co-authored by Oliver Windall Juhl
parent 0a02b70e59
commit cbbf3ca054
22 changed files with 287 additions and 96 deletions
@@ -1,21 +1,53 @@
import { pick } from "lodash"
// TODO: once the legacy totals decoration will be removed.
// We will be able to only compute the totals if one of the total fields is present
// and therefore avoid totals computation if the user don't want them to appear in the response
// and therefore the below const will be removed
const EXCLUDED_FIELDS = [
"shipping_total",
"discount_total",
"tax_total",
"refunded_total",
"total",
"subtotal",
"paid_total",
"refundable_amount",
"gift_card_total",
"gift_card_tax_total",
"item_tax_total",
"shipping_tax_total",
"refundable",
"original_total",
"original_tax_total",
]
/**
* Filter response data to contain props specified in the fields array.
* Filter response data to contain props specified in the `allowedProperties`.
* You can read more in the transformQuery middleware utility methods.
*
* @param data - record or an array of records in the response
* @param fields - record props allowed in the response
*/
function cleanResponseData<T>(data: T, fields: string[]) {
function cleanResponseData<T extends unknown | unknown[]>(
data: T,
fields: string[]
): T extends [] ? Partial<T>[] : Partial<T> {
if (!fields.length) {
return data
return data as T extends [] ? Partial<T>[] : Partial<T>
}
if (Array.isArray(data)) {
return data.map((record) => pick(record, fields))
}
const isDataArray = Array.isArray(data)
const fieldsSet = new Set([...fields, ...EXCLUDED_FIELDS])
return pick(data, fields)
fields = [...fieldsSet]
let arrayData: Partial<T>[] = isDataArray ? data : [data]
arrayData = arrayData.map((record) => pick(record, fields))
return (isDataArray ? arrayData : arrayData[0]) as T extends []
? Partial<T>[]
: Partial<T>
}
export { cleanResponseData }