@statezero/core
Version:
The type-safe frontend client for StateZero - connect directly to your backend models with zero boilerplate
49 lines (48 loc) • 1.46 kB
JavaScript
import Handlebars from 'handlebars';
import superjson from 'superjson';
// Simple map to store temporary PK to real PK mappings
export const tempPkMap = new Map();
/**
* Check if a string contains a temporary PK template
* @param {string} str - The string to check
* @returns {boolean} - True if the string contains a TempPK tag
*/
export function containsTempPk(str) {
return (typeof str === 'string' &&
/\{\{\s*TempPK_[^}\s]+\s*\}\}/.test(str));
}
/**
* Create a temporary PK with handlebars syntax
*/
export function createTempPk(uuid) {
const tempPk = `{{TempPK_${uuid}}}`;
return tempPk;
}
/**
* Register a real PK for a temporary PK
*/
export function setRealPk(uuid, realPk) {
const key = `TempPK_${uuid}`;
tempPkMap.set(key, realPk);
}
/**
* Replace all temporary PKs in an object (or string) with their real values
*/
export function replaceTempPks(payload) {
if (tempPkMap.size === 0)
return payload;
const context = Object.fromEntries(tempPkMap);
try {
if (typeof payload === 'string') {
const template = Handlebars.compile(payload, { noEscape: true });
return template(context);
}
const str = superjson.stringify(payload);
const template = Handlebars.compile(str, { noEscape: true });
const replaced = template(context);
return superjson.parse(replaced);
}
catch (error) {
return payload;
}
}