Merged buffer json reading and validation under the same function. Now it is used for pass.json and personalization.json

This commit is contained in:
Alexander Cerutti
2021-10-08 23:27:57 +02:00
parent 968d3a019c
commit c494ff9012

View File

@@ -356,7 +356,9 @@ export default class PKPass extends Bundle {
return; return;
} }
this[importMetadataSymbol](readPassMetadata(buffer)); this[importMetadataSymbol](
validateJSONBuffer(buffer, Schemas.PassProps),
);
/** /**
* Adding an empty buffer just for reference * Adding an empty buffer just for reference
@@ -374,12 +376,8 @@ export default class PKPass extends Bundle {
* once the pass is getting closed, if needed. * once the pass is getting closed, if needed.
*/ */
const prsJSON = JSON.parse(
buffer.toString(),
) as Schemas.Personalization;
try { try {
Schemas.assertValidity(Schemas.Personalization, prsJSON); validateJSONBuffer(buffer, Schemas.Personalization);
} catch (err) { } catch (err) {
console.warn( console.warn(
"Personalization.json file has been omitted as invalid.", "Personalization.json file has been omitted as invalid.",
@@ -879,16 +877,17 @@ function freezeRecusive(object: Object) {
return Object.freeze(objectCopy); return Object.freeze(objectCopy);
} }
function readPassMetadata(buffer: Buffer) { function validateJSONBuffer(
let contentAsJSON: Schemas.PassProps; buffer: Buffer,
schema: Parameters<typeof Schemas.validate>[0],
) {
let contentAsJSON: unknown;
try { try {
contentAsJSON = JSON.parse( contentAsJSON = JSON.parse(buffer.toString("utf8"));
buffer.toString("utf8"),
) as Schemas.PassProps;
} catch (err) { } catch (err) {
throw new TypeError("Cannot validat Pass.json: invalid JSON"); throw new TypeError("Cannot validat Pass.json: invalid JSON");
} }
return Schemas.validate(Schemas.PassProps, contentAsJSON); return Schemas.validate(schema, contentAsJSON);
} }