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 0342134
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
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
19 changes: 19 additions & 0 deletions packages/babel-types/src/definitions/utils.js
Expand Up @@ -161,6 +161,25 @@ export function assertValueType(type: string): Validator {
return validate;
}

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

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

0 comments on commit 0342134

Please sign in to comment.