Skip to content

Commit

Permalink
add assertShape to validate templateElement
Browse files Browse the repository at this point in the history
  • Loading branch information
tanhauhau committed Jul 11, 2019
1 parent 4eab157 commit 5dc839d
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
13 changes: 13 additions & 0 deletions packages/babel-types/scripts/utils/stringifyValidator.js
Expand Up @@ -31,6 +31,19 @@ module.exports = function stringifyValidator(validator, nodePrefix) {
return validator.type;
}

if (validator.shapeOf) {
return (
"{" +
Object.keys(validator.shapeOf)
.map(
shapeKey =>
shapeKey + ":" + stringifyValidator(validator.shapeOf[shapeKey])
)
.join(", ") +
"}"
);
}

return ["any"];
};

Expand Down
6 changes: 5 additions & 1 deletion packages/babel-types/src/definitions/es2015.js
@@ -1,5 +1,6 @@
// @flow
import defineType, {
assertShape,
assertNodeType,
assertValueType,
chain,
Expand Down Expand Up @@ -537,7 +538,10 @@ defineType("TemplateElement", {
builder: ["value", "tail"],
fields: {
value: {
// todo: flatten `raw` into main node
validate: assertShape({
raw: assertValueType("string"),
cooked: assertValueType("string"),
}),
},
tail: {
validate: assertValueType("boolean"),
Expand Down
29 changes: 29 additions & 0 deletions packages/babel-types/src/definitions/utils.js
Expand Up @@ -161,6 +161,35 @@ export function assertValueType(type: string): Validator {
return validate;
}

export function assertShape(shape: {| [string]: Validator |}): Validator {
function validate(node, key, val) {
const errors = [];
for (const property of Object.keys(shape)) {
try {
const validator = shape[property];
validator(node, property, val[property]);
} catch (error) {
if (error instanceof TypeError) {
errors.push(error.message);
continue;
}
throw error;
}
}
if (errors.length) {
throw new TypeError(
`Property ${key} of ${
node.type
} expected to have the following:\n${errors.join("\n")}`,
);
}
}

validate.shapeOf = shape;

return validate;
}

export function chain(...fns: Array<Validator>): Validator {
function validate(...args) {
for (const fn of fns) {
Expand Down

0 comments on commit 5dc839d

Please sign in to comment.