|
import { BaseRecord } from '../../adapters/index.js' |
|
import PropertyDecorator from '../../decorators/property/property-decorator.js' |
|
import { ActionContext } from '../../actions/index.js' |
|
|
|
const isValueSearchable = (value: any): value is string | number => ( |
|
['string', 'bigint', 'number'].includes(typeof value) |
|
&& value !== null |
|
&& value !== '' |
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export async function populateProperty( |
|
records: Array<BaseRecord> | null, |
|
property: PropertyDecorator, |
|
context?: ActionContext, |
|
): Promise<Array<BaseRecord> | null> { |
|
const decoratedResource = property.resource() |
|
|
|
if (!records || !records.length) { |
|
return records |
|
} |
|
|
|
const referencedResource = property.reference() |
|
|
|
if (!referencedResource) { |
|
throw new Error([ |
|
`There is no reference resource named: "${property.property.reference}"`, |
|
`for property: "${decoratedResource.id()}.properties.${property.propertyPath}"`, |
|
].join('\n')) |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const externalIdsMap = records.reduce((memo, baseRecord) => { |
|
const foreignKeyValue = baseRecord.get(property.propertyPath, { includeAllSiblings: true }) |
|
|
|
|
|
|
|
|
|
|
|
if (Array.isArray(foreignKeyValue)) { |
|
return foreignKeyValue.reduce((arrayMemo, valueInArray) => ({ |
|
...arrayMemo, |
|
...(isValueSearchable(valueInArray) ? { [valueInArray]: valueInArray } : {}), |
|
}), memo) |
|
} |
|
|
|
if (!isValueSearchable(foreignKeyValue)) { |
|
return memo |
|
} |
|
|
|
memo[foreignKeyValue] = foreignKeyValue |
|
|
|
return memo |
|
}, {}) |
|
|
|
const uniqueExternalIds = Object.values<string | number>(externalIdsMap) |
|
|
|
|
|
if (!uniqueExternalIds.length) { |
|
return records |
|
} |
|
|
|
|
|
const referenceRecords = await referencedResource.findMany(uniqueExternalIds, context) |
|
|
|
|
|
|
|
if (!referenceRecords || !referenceRecords.length) { |
|
return records |
|
} |
|
|
|
|
|
|
|
|
|
referenceRecords.forEach((referenceRecord) => { |
|
|
|
const foreignKeyValue = referenceRecord.id() |
|
externalIdsMap[foreignKeyValue] = referenceRecord |
|
}) |
|
|
|
return records.map((record) => { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const referenceParams = record.selectParams(property.propertyPath, { |
|
includeAllSiblings: true, |
|
}) || {} |
|
|
|
|
|
|
|
Object.entries(referenceParams).forEach(([path, foreignKeyValueItem]) => { |
|
record.populate(path, externalIdsMap[foreignKeyValueItem]) |
|
}) |
|
|
|
return record |
|
}) |
|
} |
|
|