UNPKG

2.46 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.deepResolveMockList = exports.MockList = exports.isMockList = void 0;
4/**
5 * @internal
6 */
7function isMockList(obj) {
8 if (typeof (obj === null || obj === void 0 ? void 0 : obj.len) === 'number' || (Array.isArray(obj === null || obj === void 0 ? void 0 : obj.len) && typeof (obj === null || obj === void 0 ? void 0 : obj.len[0]) === 'number')) {
9 if (typeof obj.wrappedFunction === 'undefined' || typeof obj.wrappedFunction === 'function') {
10 return true;
11 }
12 }
13 return false;
14}
15exports.isMockList = isMockList;
16/**
17 * This is an object you can return from your mock resolvers which calls the
18 * provided `mockFunction` once for each list item.
19 */
20class MockList {
21 /**
22 * @param length Either the exact length of items to return or an inclusive
23 * range of possible lengths.
24 * @param mockFunction The function to call for each item in the list to
25 * resolve it. It can return another MockList or a value.
26 */
27 constructor(length, mockFunction) {
28 this.len = length;
29 if (typeof mockFunction !== 'undefined') {
30 if (typeof mockFunction !== 'function') {
31 throw new Error('Second argument to MockList must be a function or undefined');
32 }
33 this.wrappedFunction = mockFunction;
34 }
35 }
36 /**
37 * @internal
38 */
39 mock() {
40 let arr;
41 if (Array.isArray(this.len)) {
42 arr = new Array(this.randint(this.len[0], this.len[1]));
43 }
44 else {
45 arr = new Array(this.len);
46 }
47 for (let i = 0; i < arr.length; i++) {
48 if (typeof this.wrappedFunction === 'function') {
49 const res = this.wrappedFunction();
50 if (isMockList(res)) {
51 arr[i] = res.mock();
52 }
53 else {
54 arr[i] = res;
55 }
56 }
57 else {
58 arr[i] = undefined;
59 }
60 }
61 return arr;
62 }
63 randint(low, high) {
64 return Math.floor(Math.random() * (high - low + 1) + low);
65 }
66}
67exports.MockList = MockList;
68function deepResolveMockList(mockList) {
69 return mockList.mock().map(v => {
70 if (isMockList(v))
71 return deepResolveMockList(v);
72 return v;
73 });
74}
75exports.deepResolveMockList = deepResolveMockList;