Skip to content

检查

¥Check

有关如何使用 Meteor 的类型检查库 check 的文档。

¥Documentation on how to use check, Meteor's type checking library.

check 包包含模式检查函数,可用于检查变量的类型和结构,以及 可扩展模式库,用于指定你期望的类型。

¥The check package includes pattern checking functions useful for checking the types and structure of variables and an extensible library of patterns to specify which types you are expecting.

要将 check(或 Match)添加到你的应用,请在你的终端中运行此命令:

¥To add check (or Match) to your application, run this command in your terminal:

bash
meteor add check

check

Summary:

Check that a value matches a pattern. If the value does not match the pattern, throw a Match.Error. By default, it will throw immediately at the first error encountered. Pass in { throwAllErrors: true } to throw all errors.

Particularly useful to assert that arguments to a function have the right types and structure.

Arguments:

Source code
NameTypeDescriptionRequired
valueAny

The value to check

Yes
patternMatchPattern

The pattern to match value against

Yes
optionsObject

Additional options for check

No

Options:

NameTypeDescriptionRequired
throwAllErrorsBoolean

If true, throw all errors

No

Meteor 方法和发布函数可以将任意 EJSON 类型作为参数,但大多数函数都希望它们的参数属于特定类型。check 是一个轻量级函数,用于检查参数和其他值是否属于预期类型。例如:

¥Meteor methods and publish functions can take arbitrary EJSON types as arguments, but most functions expect their arguments to be of a particular type. check is a lightweight function for checking that arguments and other values are of the expected type. For example:

js
import { check } from "meteor/check";
import { Meteor } from "meteor/meteor";
Meteor.publish("chatsInRoom", function (roomId) {
  // Make sure `roomId` is a string, not an arbitrary Mongo selector object.
  check(roomId, String);
  return Chats.find({ room: roomId });
});

Meteor.methods({
  addChat(roomId, message) {
    check(roomId, String);
    check(message, {
      text: String,
      timestamp: Date,
      // Optional, but if present must be an array of strings.
      tags: Match.Maybe([String]),
    });

    // Do something with the message...
  },
});

如果匹配失败,check 将抛出一个 Match.Error 来描述它是如何失败的。如果此错误通过网络发送到客户端,它将仅显示为 Meteor.Error(400, 'Match Failed')。失败详细信息将写入服务器日志,但不会显示给客户端。

¥If the match fails, check throws a Match.Error describing how it failed. If this error gets sent over the wire to the client, it will appear only as Meteor.Error(400, 'Match Failed'). The failure details will be written to the server logs but not revealed to the client.

Match.test

Summary:

Returns true if the value matches the pattern.

Arguments:

Source code
NameTypeDescriptionRequired
valueAny

The value to check

Yes
patternMatchPattern

The pattern to match value against

Yes

Match.test 可用于识别变量是否具有某种结构。

¥Match.test can be used to identify if a variable has a certain structure.

js
import { Match } from "meteor/check";

// Will return true for `{ foo: 1, bar: 'hello' }` or similar.
Match.test(value, { foo: Match.Integer, bar: String });

// Will return true if `value` is a string.
Match.test(value, String);

// Will return true if `value` is a string or an array of numbers.
Match.test(value, Match.OneOf(String, [Number]));

如果你有一个接受几种不同类型对象的函数,并且想要确定传入了哪些对象,那么这将非常有用。

¥This can be useful if you have a function that accepts several different kinds of objects, and you want to determine which was passed in.

匹配模式

¥Match Patterns

以下模式可用作 checkMatch.test 的模式参数:

¥The following patterns can be used as pattern arguments to check and Match.test:

Match.Any

匹配任何值。

¥Matches any value.

js
import { Match } from "meteor/check";
// Will return true for any value.
Match.test(value, Match.Any);

String, Number, Boolean, undefined, null

匹配给定类型的原语。

¥Matches a primitive of the given type.

js
import { Match } from "meteor/check";
let result;
// Will return true if `value` is a string.
result = Match.test(value, String);
console.log(result); // true

// Will return true if `value` is a number.
result = Match.test(value, Number);
console.log(result); // true

// Will return true if `value` is a boolean.
result = Match.test(value, Boolean);
console.log(result); // true

Match.Integer

匹配有符号的 32 位整数。与 Infinity-InfinityNaN 不匹配。

¥Matches a signed 32-bit integer. Doesn't match Infinity, -Infinity, or NaN.

js
import { Match } from "meteor/check";
let result;
// Will return true if `value` is an integer.
result = Match.test(value, Match.Integer);
console.log(result); // true

[pattern]

一个元素数组与元素数组匹配,每个元素都与模式匹配。例如,[Number] 匹配(可能为空的)数字数组;[Match.Any] 匹配任何数组。

¥A one-element array matches an array of elements, each of which match pattern. For example, [Number] matches a (possibly empty) array of numbers; [Match.Any] matches any array.

js
import { Match } from "meteor/check";
let result;
// Will return true if `value` is an array of numbers.
result = Match.test(value, [Number]);
console.log(result); // true

{ key1: pattern1, key2: pattern2, ... }

匹配具有给定键的对象,其值与给定模式匹配。如果任何模式是 Match.MaybeMatch.Optional,则该键不需要存在于对象中。该值不得包含模式中未列出的任何键。该值必须是没有特殊原型的普通对象。

¥Matches an Object with the given keys, with values matching the given patterns. If any pattern is a Match.Maybe or Match.Optional, that key does not need to exist in the object. The value may not contain any keys not listed in the pattern. The value must be a plain Object with no special prototype.

js
import { Match } from "meteor/check";
let result;
// Will return true if `value` is an object with keys 'foo' and 'bar'.
result = Match.test(value, { foo: String, bar: Number });
console.log(result); // true

Match.ObjectIncluding({ key1: pattern1, key2: pattern2, ... })

匹配具有给定键的对象;该值还可以包含其他具有任意值的键。

¥Matches an Object with the given keys; the value may also have other keys with arbitrary values.

js
import { Match } from "meteor/check";
let result;
// Will return true if `value` is an object with keys 'foo' and 'bar'.
result = Match.test(value, Match.ObjectIncluding({ foo: String, bar: Number }));
console.log(result); // true

Object

匹配任何具有任意键的普通对象;相当于 Match.ObjectIncluding({})

¥Matches any plain Object with any keys; equivalent to Match.ObjectIncluding({}).

js
import { Match } from "meteor/check";
let result;
// Will return true if `value` is an object.
result = Match.test(value, Object);
console.log(result); // true

Match.Maybe(pattern)

匹配 undefinednull 或模式。如果在对象中使用,则仅当未设置键而不是将值设置为 undefinednull 时才匹配。之所以选择这组条件,是因为 Meteor 方法的 undefined 参数在通过网络发送时会转换为 null

¥Matches either undefined, null, or pattern. If used in an object, matches only if the key is not set as opposed to the value being set to undefined or null. This set of conditions was chosen because undefined arguments to Meteor Methods are converted to null when sent over the wire.

js
import { Match, check } from "meteor/check";
// In an object
const pattern = { name: Match.Maybe(String) };

check({ name: "something" }, pattern); // OK
check({}, pattern); // OK
check({ name: undefined }, pattern); // Throws an exception
check({ name: null }, pattern); // Throws an exception

// Outside an object
check(null, Match.Maybe(String)); // OK
check(undefined, Match.Maybe(String)); // OK

Match.Optional(pattern)

行为类似于 Match.Maybe,但不接受 null。如果在对象中使用,行为与 Match.Maybe 相同。

¥Behaves like Match.Maybe except it doesn't accept null. If used in an object, the behavior is identical to Match.Maybe.

Match.OneOf(pattern1, pattern2, ...)

匹配至少匹配一个所提供模式的任意值。

¥Matches any value that matches at least one of the provided patterns.

任何构造函数(例如,Date

¥Any constructor function (eg, Date)

匹配任何属于该类型实例的元素。

¥Matches any element that is an instance of that type.

js
import { Match } from "meteor/check";
let result;

// Will return true if `value` is a Date.
result = Match.test(value, Date);

Match.Where(condition)

使用值作为参数调用函数条件。如果条件返回 true,则匹配。如果条件抛出 Match.Error 或返回 false,则失败。如果条件引发任何其他错误,则该错误将从对 checkMatch.test 的调用中引发。示例:

¥Calls the function condition with the value as the argument. If condition returns true, this matches. If condition throws a Match.Error or returns false, this fails. If condition throws any other error, that error is thrown from the call to check or Match.test. Examples:

js
import { Match, check } from "meteor/check";

check(buffer, Match.Where(EJSON.isBinary));

const NonEmptyString = Match.Where((x) => {
  check(x, String);
  return x.length > 0;
});

check(arg, NonEmptyString);