validateObjectWithKeys
Description
Similar to the validateObjectWithExistingKey function, this function will allow you to pass a list of keys you are expecting an object to have. If ALL keys from the parameter list is contained in the object, this function will resolve the object.
Please, note that the tuple parameter is not optional. If don't intend to use the tuple, assign it undefined.
Parameter List | Returns | Rejection Errors |
---|---|---|
| Promise<object || Array> | |
Related Functions | Function Signature | |
function validateObjectWithKeys(object, tuple, ...desiredKeys): Promise<object || Array> |
Examples
1
2
3
4
5
import { validateObjectWithKeys } from "puddy-m/lib/validators/complexValidators";
validateObjectWithKeys({ foo: "bar", fizz: "buzz" }, null, "foo", "fizz").then(
console.log
); // prints { foo: "bar", fizz: "buzz" }
1
2
3
4
5
6
import { validateString } from "puddy-m/lib/validators";
import { validateObjectWithKeys } from "puddy-m/lib/validators/complexValidators";
validateObjectWithKeys({ someKey: "foo", anotherKey: "bar" }, [], "someKey")
.then((tuple) => validateString("foo", tuple))
.then(console.log); // prints [{ someKey: "foo", anotherKey: "bar" }, "foo"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { validateObjectWithKeys } from "puddy-m/lib/validators/complexValidators";
const run = async () => {
try {
const obj = await validateObjectWithKeys(
{ a: "a", b: "b" },
null,
"a",
"b"
);
console.log(obj); // prints "a"
} catch (e) {
console.log(e);
}
};
run();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { validateObjectWithKeys } from "puddy-m/lib/validators/complexValidators";
const run = async () => {
try {
const obj = await validateObjectWithKeys(
{ a: "a" },
null,
"a",
"nonExstingKey"
);
console.log(obj); // Because keys doesn't exist in object, it will throw
} catch (e) {
// Throw ObjectWithKeysValidationError
console.log(e);
}
};
run();