safe-json-value
Version:
⛑️ JSON serialization should never fail
80 lines (61 loc) • 1.22 kB
JavaScript
import normalizeException from"normalize-exception";
export const safeGetChangeProp=({parent,key})=>{
try{
return parent[key]
}catch{}
};
export const safeGetProp=({parent,key,changes,path})=>{
try{
const prop=getProp({parent,key,changes,path});
return{prop,safe:true}
}catch(error){
changes.push({
path,
oldValue:undefined,
newValue:undefined,
reason:"unsafeGetter",
error:normalizeException(error)
});
return{prop:undefined,safe:false}
}
};
const getProp=({parent,key,changes,path})=>{
const descriptor=Object.getOwnPropertyDescriptor(parent,key);
const prop=parent[key];
addGetterChange({changes,path,prop,descriptor});
addDescriptorChange({changes,path,prop,descriptor});
return prop
};
const addGetterChange=({changes,path,prop,descriptor:{get,set}})=>{
if(get!==undefined||set!==undefined){
changes.push({
path,
oldValue:get,
newValue:prop,
reason:"unresolvedGetter"
})
}
};
const addDescriptorChange=({
changes,
path,
prop,
descriptor:{writable,configurable}
})=>{
if(writable===false){
changes.push({
path,
oldValue:prop,
newValue:prop,
reason:"descriptorNotWritable"
})
}
if(configurable===false){
changes.push({
path,
oldValue:prop,
newValue:prop,
reason:"descriptorNotConfigurable"
})
}
};