You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Just discovered this awesome library. Just what I was looking for! Thanks very much.
I had a look at the code for the object decoder and noted that it iterates over the fields of the fields of the object specification and returns as a result only these fields. That great for cleaning JSON input values, however I often need to check that fields in the input json object are only those defined by the object decoder. To support this I think we need a strict argument on the object() decoder that checks and reports an error if any additional fields are found in the json object.
staticobject<A>(decoders?: DecoderObject<A>,strict?: boolean=false){returnnewDecoder((json: unknown)=>{if(isJsonObject(json)&&decoders){letobj: any={};for(constkeyindecoders){if(decoders.hasOwnProperty(key)){constr=decoders[key].decode(json[key]);if(r.ok===true){// tslint:disable-next-line:strict-type-predicatesif(r.result!==undefined){obj[key]=r.result;}}elseif(json[key]===undefined){returnResult.err({message: `the key '${key}' is required but was not present`});}else{returnResult.err(prependAt(`.${key}`,r.error));}}}// ADDEDif(strict){for(constkeyinjson){if(!decoders.hasOwnProperty(key)){returnResult.err({message: `an undefined key '${key}' is present in the object`});}}}returnResult.ok(obj);}elseif(isJsonObject(json)){returnResult.ok(json);}else{returnResult.err({message: expectedGot('an object',json)});}});}
The text was updated successfully, but these errors were encountered:
Actually I think there a more functional approach that you'd probably recommend.
We just add a strictObject(decoders) function that invokes object(decoders).
Here's my untested JavaScript (not TypeScript) version
constcheckStrict=(decoders)=>{returnnewDecoder((json)=>{for(constkeyinjson){if(!decoders.hasOwnProperty(key)){returnResult.err({message: `an undefined key '${key}' is present in the object`});}}returnResult.ok(json);});}// like object() but checks that only declared fields are used.exportconststrictObject=(decoders)=>object(decoders).andThen(checkStrict(decoders));
Just discovered this awesome library. Just what I was looking for! Thanks very much.
I had a look at the code for the object decoder and noted that it iterates over the fields of the fields of the object specification and returns as a result only these fields. That great for cleaning JSON input values, however I often need to check that fields in the input
json
object are only those defined by the object decoder. To support this I think we need astrict
argument on the object() decoder that checks and reports an error if any additional fields are found in thejson
object.The text was updated successfully, but these errors were encountered: