Created
February 28, 2024 02:38
-
-
Save marcosleal-prd/02455378aaf00de15fc39c55793c2e04 to your computer and use it in GitHub Desktop.
Mapping fields based on entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export enum MappingMode { | |
SEND = 'send', | |
RECEIVE = 'receive' | |
} | |
export type MappingEntity = 'contact' | 'deal' | 'organization' | |
export type FieldMapping = { | |
sourceField: string | |
destinationField: string | |
} | |
export type FieldMappings = Record<MappingEntity, FieldMapping[]> | |
export class FieldMappingService { | |
applyMapping( | |
data: Record<string, unknown>, | |
mappings: FieldMappings, | |
entity: MappingEntity, | |
mode: MappingMode = MappingMode.RECEIVE | |
): Record<string, unknown> { | |
const entityFieldMappings = mappings[entity] | |
if (!entityFieldMappings || !entityFieldMappings.length) { | |
return data | |
} | |
const newData: Record<string, unknown> = { ...data } | |
entityFieldMappings.forEach(({ sourceField, destinationField }) => { | |
let sourcePath: string[] = sourceField.split('.') | |
let destinationPath: string[] = destinationField.split('.') | |
if (mode === MappingMode.SEND) { | |
sourcePath = destinationField.split('.') | |
destinationPath = sourceField.split('.') | |
} | |
let value = newData | |
sourcePath.forEach(path => { | |
if (value && typeof value === 'object' && path in value) { | |
value = value[path] | |
} else { | |
value = undefined | |
} | |
}) | |
if (value !== undefined) { | |
let obj = newData | |
for (let i = 0; i < destinationPath.length - 1; i++) { | |
const key = destinationPath[i] | |
obj[key] = obj[key] || {} | |
obj = obj[key] | |
} | |
obj[destinationPath[destinationPath.length - 1]] = value | |
} | |
}) | |
return newData | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment