import type { Source, Record, Shape } from '@servicenow/sdk-build-core' import { NowIdShape } from '../now-id-plugin' export const getExplicitIdGenerator = (source: Source, appConfigId: string) => (table: string, uniqueString: string) => new NowIdShape({ source, id: `${appConfigId}_${table}_${uniqueString}` }) export const buildRecordKey = (record: Record) => `${record.getTable()}_${record.getId().getValue()}` /* This is just an equality check similar to the existing "strictEqual", except it's a little more relaxed. We want to make sure that our defaulted records aren't "tampered" with. If they are, this will detect it. Record.strictEqual() tests that the number of properties match, which is too agressive for our needs, because the number of properties on an actual record is almost always higher than on a generated record (due to sys_ columns, mostly). */ export const doesActualRecordMatchGeneratedRecord = (actualRecord: Record, generatedRecord: Record): boolean => { for (const [gFieldName, gFieldValue] of generatedRecord.entries()) { const generatedRecordValueAsString = convertFieldValueToString(gFieldValue) const actualRecordValueAsString = convertFieldValueToString(actualRecord.get(gFieldName)) if (generatedRecordValueAsString !== actualRecordValueAsString) { return false } } return true } export const convertFieldValueToString = (fieldValue: Shape): string => { if (fieldValue.isRecord()) { return fieldValue.asRecord().getId().getValue() } else if (fieldValue.isBoolean()) { return fieldValue.asBoolean().getValue().toString() } else if (fieldValue.isNumber()) { return fieldValue.asNumber().getValue().toString() } return fieldValue.asString().getValue() } export const serializeActualRecordAsOverrideToTheDefault = ( actualRecord: Record, generatedRecord: Record ): { [fieldName: string]: string } => { // Looping through the generated record keys gives us a more controllable and precise list to track/record. const serializedRecordValue: { [fieldName: string]: string } = {} for (const field of generatedRecord.keys()) { const fieldValue = actualRecord.get(field) if (fieldValue.isRecord()) { serializedRecordValue[field] = fieldValue.asRecord().getId().getValue() } else { try { serializedRecordValue[field] = JSON.stringify(JSON.parse(fieldValue.asString().getValue())).replace( /\\/g, '\\\\' ) } catch (e) { serializedRecordValue[field] = fieldValue.asString().getValue() } } } return serializedRecordValue }