UNPKG

1.67 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2017,2019. All Rights Reserved.
3// Node module: @loopback/repository
4// This file is licensed under the MIT License.
5// License text available at https://opensource.org/licenses/MIT
6Object.defineProperty(exports, "__esModule", { value: true });
7exports.UnionType = void 0;
8const tslib_1 = require("tslib");
9const util_1 = tslib_1.__importDefault(require("util"));
10/* eslint-disable @typescript-eslint/no-explicit-any */
11/**
12 * Union type, such as string | number
13 */
14class UnionType {
15 constructor(itemTypes) {
16 this.itemTypes = itemTypes;
17 this.name = 'union';
18 }
19 isInstance(value) {
20 return this.itemTypes.some(t => t.isInstance(value));
21 }
22 isCoercible(value) {
23 return this.itemTypes.some(t => t.isCoercible(value));
24 }
25 defaultValue() {
26 return this.itemTypes[0].defaultValue();
27 }
28 coerce(value) {
29 // First find instances
30 for (const type of this.itemTypes) {
31 if (type.isInstance(value)) {
32 return type.coerce(value);
33 }
34 }
35 // Try coercible
36 for (const type of this.itemTypes) {
37 if (type.isCoercible(value)) {
38 return type.coerce(value);
39 }
40 }
41 const msg = util_1.default.format('Invalid %s: %j', this.name, value);
42 throw new TypeError(msg);
43 }
44 serialize(value) {
45 for (const type of this.itemTypes) {
46 if (type.isInstance(value)) {
47 return type.serialize(value);
48 }
49 }
50 }
51}
52exports.UnionType = UnionType;
53//# sourceMappingURL=union.js.map
\No newline at end of file