prisma-mock 0.0.7 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -79,6 +79,7 @@ const createPrismaMock = async (data = {}, pathToSchema, client = (0, jest_mock_
79
79
  return getCamelCase(model.name) === prop;
80
80
  });
81
81
  model.fields.forEach(field => {
82
+ d; //?
82
83
  if (d[field.name] && field.kind === 'object') {
83
84
  const c = d[field.name];
84
85
  if (c.connect) {
@@ -112,7 +113,12 @@ const createPrismaMock = async (data = {}, pathToSchema, client = (0, jest_mock_
112
113
  delegate.createMany(Object.assign(Object.assign({}, c.createMany), { data: c.createMany.data.map(map) }));
113
114
  }
114
115
  else {
115
- delegate.create(Object.assign(Object.assign({}, create.create), { data: map(create.create) }));
116
+ if (Array.isArray(c.create)) {
117
+ delegate.createMany(Object.assign(Object.assign({}, c.create), { data: c.create.map(map) }));
118
+ }
119
+ else {
120
+ delegate.create(Object.assign(Object.assign({}, create.create), { data: map(create.create) }));
121
+ }
116
122
  }
117
123
  }
118
124
  }
@@ -283,6 +289,7 @@ const createPrismaMock = async (data = {}, pathToSchema, client = (0, jest_mock_
283
289
  const create = args => {
284
290
  const d = nestedUpdate(args, true);
285
291
  data = Object.assign(Object.assign({}, data), { [prop]: [...data[prop], d] });
292
+ data; //?
286
293
  data = checkIds(model, data);
287
294
  return findOne(Object.assign({ where: { id: d.id } }, args));
288
295
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prisma-mock",
3
- "version": "0.0.7",
3
+ "version": "0.0.10",
4
4
  "description": "Mock prisma for unit testing database",
5
5
  "main": "lib/index.js",
6
6
  "license": "MIT",
@@ -1 +0,0 @@
1
- export {};
@@ -1,40 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- const __1 = __importDefault(require("../"));
8
- describe("PrismaClient distinct", () => {
9
- const data = {
10
- user: [
11
- {
12
- id: 1,
13
- name: "Piet",
14
- },
15
- {
16
- id: 2,
17
- name: "Piet",
18
- },
19
- {
20
- id: 3,
21
- name: "Henk",
22
- },
23
- {
24
- id: 4,
25
- name: "Henk",
26
- },
27
- ],
28
- };
29
- test("distinct", async () => {
30
- const client = await (0, __1.default)(data);
31
- let users = await client.user.findMany({
32
- distinct: ['id']
33
- });
34
- expect(users.length).toBe(4);
35
- users = await client.user.findMany({
36
- distinct: ['name']
37
- });
38
- expect(users.length).toBe(2);
39
- });
40
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,78 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- const __1 = __importDefault(require("../"));
8
- describe('PrismaClient @@id()', () => {
9
- const data = {
10
- user: [
11
- {
12
- id: 1,
13
- name: 'sadfsdf',
14
- }
15
- ],
16
- userAnswers: [
17
- {
18
- userId: 1,
19
- answerId: 2
20
- }
21
- ],
22
- answers: [
23
- {
24
- id: 1,
25
- title: "Answer"
26
- },
27
- {
28
- id: 2,
29
- title: "Answer"
30
- }
31
- ],
32
- };
33
- test('findOne', async () => {
34
- const client = await (0, __1.default)(data);
35
- const user = await client.userAnswers.findUnique({
36
- where: {
37
- userId_answerId: {
38
- userId: 1,
39
- answerId: 2
40
- }
41
- },
42
- });
43
- expect(user).toEqual(expect.objectContaining(data.userAnswers[0]));
44
- });
45
- test('create', async () => {
46
- const client = await (0, __1.default)(data);
47
- await client.userAnswers.create({
48
- data: {
49
- user: { connect: { id: 1 } },
50
- answer: { connect: { id: 1 } },
51
- }
52
- });
53
- const user = await client.userAnswers.findUnique({
54
- where: {
55
- userId_answerId: {
56
- userId: 1,
57
- answerId: 1
58
- }
59
- },
60
- });
61
- expect(user).toEqual(expect.objectContaining({
62
- userId_answerId: {
63
- userId: 1,
64
- answerId: 1
65
- }
66
- }));
67
- });
68
- test('delete', async () => {
69
- });
70
- test('update', async () => {
71
- });
72
- test('upsert update', async () => {
73
- });
74
- test('upsert insert', async () => {
75
- });
76
- test.todo("connect");
77
- test.todo('should throw when there is a duplicate');
78
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,104 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- const __1 = __importDefault(require("../"));
8
- describe("PrismaClient include", () => {
9
- const data = {
10
- user: [
11
- {
12
- id: 1,
13
- name: "sadfsdf",
14
- accountId: 1,
15
- },
16
- ],
17
- account: [
18
- {
19
- id: 1,
20
- name: "sadfsdf",
21
- },
22
- {
23
- id: 2,
24
- name: "adsfasdf2",
25
- },
26
- ],
27
- stripe: [
28
- {
29
- id: 1,
30
- accountId: 1,
31
- },
32
- ],
33
- };
34
- test("findOne to", async () => {
35
- const client = await (0, __1.default)(data);
36
- const user = await client.user.findUnique({
37
- where: {
38
- id: 1,
39
- },
40
- include: {
41
- account: true,
42
- },
43
- });
44
- expect(user).toEqual(Object.assign(Object.assign({}, data.user[0]), { account: data.account[0] }));
45
- });
46
- test("findOne from", async () => {
47
- const client = await (0, __1.default)(data);
48
- const stripe = await client.stripe.findUnique({
49
- where: {
50
- id: 1,
51
- },
52
- include: {
53
- account: true,
54
- },
55
- });
56
- expect(stripe).toEqual(Object.assign(Object.assign({}, data.stripe[0]), { account: data.account[0] }));
57
- });
58
- test("findOne deep", async () => {
59
- const client = await (0, __1.default)(data);
60
- const user = await client.user.findUnique({
61
- where: {
62
- id: 1,
63
- },
64
- include: {
65
- account: {
66
- include: {
67
- stripe: true,
68
- },
69
- },
70
- },
71
- });
72
- expect(user).toEqual(Object.assign(Object.assign({}, data.user[0]), { account: Object.assign(Object.assign({}, data.account[0]), { stripe: data.stripe[0] }) }));
73
- });
74
- test("findMany deep", async () => {
75
- const client = await (0, __1.default)(data);
76
- const users = await client.user.findMany({
77
- where: {
78
- id: 1,
79
- },
80
- include: {
81
- account: {
82
- include: {
83
- stripe: true,
84
- },
85
- },
86
- },
87
- });
88
- expect(users[0]).toEqual(Object.assign(Object.assign({}, data.user[0]), { account: Object.assign(Object.assign({}, data.account[0]), { stripe: data.stripe[0] }) }));
89
- });
90
- test("findMany one to many", async () => {
91
- const client = await (0, __1.default)(data);
92
- const users = await client.account.findMany({
93
- where: {
94
- id: 1,
95
- },
96
- include: {
97
- users: true
98
- },
99
- });
100
- expect(users[0]).toEqual(Object.assign(Object.assign({}, data.account[0]), { users: [
101
- data.user[0],
102
- ] }));
103
- });
104
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,169 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- const __1 = __importDefault(require("../"));
8
- describe('PrismaClient', () => {
9
- const data = {
10
- user: [
11
- {
12
- id: 1,
13
- name: 'sadfsdf',
14
- accountId: 1,
15
- role: "ADMIN"
16
- }
17
- ],
18
- account: [
19
- {
20
- id: 1,
21
- name: 'sadfsdf',
22
- },
23
- {
24
- id: 2,
25
- name: 'adsfasdf2',
26
- }
27
- ]
28
- };
29
- test('findOne', async () => {
30
- const client = await (0, __1.default)(data);
31
- const user = await client.user.findUnique({
32
- where: {
33
- id: 1
34
- }
35
- });
36
- expect(user).toBe(data.user[0]);
37
- });
38
- test('findOne by id', async () => {
39
- const client = await (0, __1.default)(data);
40
- const user = await client.account.findUnique({
41
- where: {
42
- id: 2
43
- }
44
- });
45
- expect(user).toBe(data.account[1]);
46
- });
47
- test('findMany', async () => {
48
- const client = await (0, __1.default)(data);
49
- const accounts = await client.account.findMany();
50
- expect(accounts).toEqual(data.account);
51
- });
52
- test('findFirst', async () => {
53
- const client = await (0, __1.default)(data);
54
- const accounts = await client.account.findFirst();
55
- expect(accounts).toEqual(data.account[0]);
56
- });
57
- test('count', async () => {
58
- const client = await (0, __1.default)(data);
59
- const accounts = await client.account.count();
60
- expect(accounts).toEqual(2);
61
- });
62
- test('create', async () => {
63
- const client = await (0, __1.default)(data);
64
- // TODO: Check output
65
- await client.user.create({
66
- data: {
67
- name: 'New user'
68
- }
69
- });
70
- const users = await client.user.findMany();
71
- expect(users).toEqual([
72
- ...data.user,
73
- {
74
- id: 2,
75
- name: 'New user',
76
- role: "ADMIN"
77
- }
78
- ]);
79
- });
80
- test('create connect', async () => {
81
- const client = await (0, __1.default)(data);
82
- // TODO: Check output
83
- await client.user.create({
84
- data: {
85
- name: 'New user',
86
- account: { connect: { id: 1 } }
87
- }
88
- });
89
- const users = await client.user.findMany();
90
- expect(users).toEqual([
91
- ...data.user,
92
- {
93
- id: 2,
94
- name: 'New user',
95
- role: "ADMIN",
96
- accountId: 1,
97
- }
98
- ]);
99
- });
100
- test('delete', async () => {
101
- const client = await (0, __1.default)(data);
102
- const user = await client.account.delete({
103
- where: {
104
- id: 2
105
- }
106
- });
107
- const users = await client.account.findMany();
108
- expect(users).toEqual([data.account[0]]);
109
- });
110
- test('update', async () => {
111
- const client = await (0, __1.default)(data);
112
- const user = await client.account.update({
113
- where: {
114
- id: 2
115
- },
116
- data: {
117
- name: "New name"
118
- }
119
- });
120
- const users = await client.account.findMany();
121
- expect(users).toEqual([
122
- data.account[0],
123
- {
124
- id: 2,
125
- name: "New name"
126
- }
127
- ]);
128
- });
129
- test('upsert update', async () => {
130
- const client = await (0, __1.default)(data);
131
- const user = await client.account.upsert({
132
- where: {
133
- id: 2
134
- },
135
- update: {
136
- name: "New name"
137
- }
138
- });
139
- const users = await client.account.findMany();
140
- expect(users).toEqual([
141
- data.account[0],
142
- {
143
- id: 2,
144
- name: "New name"
145
- }
146
- ]);
147
- });
148
- test('upsert insert', async () => {
149
- const client = await (0, __1.default)(data);
150
- const user = await client.account.upsert({
151
- where: {
152
- id: 3
153
- },
154
- create: {
155
- id: 3,
156
- name: "New name"
157
- }
158
- });
159
- const users = await client.account.findMany();
160
- expect(users).toEqual([
161
- ...data.account,
162
- {
163
- id: 3,
164
- name: "New name"
165
- }
166
- ]);
167
- });
168
- test.todo('connect');
169
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,246 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- const __1 = __importDefault(require("../"));
8
- describe('Nested', () => {
9
- test('create: create one-to-many', async () => {
10
- const client = await (0, __1.default)({});
11
- // TODO: Check output
12
- const account = await client.account.create({
13
- data: {
14
- users: {
15
- create: {
16
- role: "USER"
17
- },
18
- }
19
- },
20
- include: {
21
- users: true
22
- }
23
- });
24
- const users = await client.user.findMany();
25
- expect(users.length).toBe(1);
26
- expect(account).toEqual({
27
- id: 2,
28
- users: [{
29
- id: 2,
30
- accountId: 2,
31
- role: "USER"
32
- }]
33
- });
34
- });
35
- test('create: create one-to-one', async () => {
36
- const client = await (0, __1.default)({});
37
- // TODO: Check output
38
- const user = await client.user.create({
39
- data: {
40
- role: "USER",
41
- account: {
42
- create: {},
43
- }
44
- },
45
- include: {
46
- account: true
47
- }
48
- });
49
- expect(user).toEqual({
50
- id: 2,
51
- accountId: 2,
52
- role: "USER",
53
- account: {
54
- id: 2,
55
- }
56
- });
57
- });
58
- test('create: createMany', async () => {
59
- const client = await (0, __1.default)({
60
- answers: [],
61
- userAnswers: [],
62
- user: [
63
- { id: 1, role: "USER" }
64
- ]
65
- });
66
- // TODO: Check output
67
- const answer = await client.answers.create({
68
- data: {
69
- title: "Title",
70
- users: {
71
- createMany: {
72
- data: [{ userId: 1 }]
73
- },
74
- }
75
- },
76
- include: {
77
- users: true
78
- }
79
- });
80
- expect(answer).toEqual({
81
- title: "Title",
82
- id: 2,
83
- users: [{
84
- answerId: 2,
85
- userId: 1,
86
- // userId_answerId: { answerId: 2, userId: 1 },
87
- }]
88
- });
89
- });
90
- test('update: createMany', async () => {
91
- const client = await (0, __1.default)({
92
- answers: [
93
- { id: 1, title: "Title" }
94
- ],
95
- userAnswers: [],
96
- user: [
97
- { id: 1, role: "USER" }
98
- ]
99
- });
100
- // TODO: Check output
101
- const answer = await client.answers.update({
102
- data: {
103
- users: {
104
- createMany: {
105
- data: [{ userId: 1 }]
106
- },
107
- }
108
- },
109
- where: { id: 1 },
110
- include: {
111
- users: true
112
- }
113
- });
114
- expect(answer).toEqual({
115
- title: "Title",
116
- id: 1,
117
- users: [{
118
- answerId: 1,
119
- userId: 1,
120
- // TODO:
121
- // userId_answerId: { answerId: 1, userId: 1 },
122
- }]
123
- });
124
- });
125
- test('update: updateMany', async () => {
126
- const client = await (0, __1.default)({
127
- account: [
128
- { id: 1, }
129
- ],
130
- stripe: {
131
- customerId: "1",
132
- accountId: 1,
133
- },
134
- user: [
135
- { id: 2, role: "ADMIN", accountId: 1 }
136
- ]
137
- });
138
- // TODO: Check output
139
- const answer = await client.account.update({
140
- data: {
141
- users: {
142
- updateMany: [{
143
- data: {
144
- role: "USER"
145
- },
146
- where: {
147
- accountId: 1,
148
- }
149
- }]
150
- }
151
- },
152
- where: {
153
- id: 1
154
- },
155
- include: {
156
- users: true
157
- }
158
- });
159
- expect(answer).toEqual({
160
- id: 1,
161
- users: [{
162
- id: 2,
163
- accountId: 1,
164
- role: "USER"
165
- }]
166
- });
167
- });
168
- test('update: update one-to-many', async () => {
169
- const client = await (0, __1.default)({
170
- account: [
171
- { id: 1, }
172
- ],
173
- stripe: {
174
- customerId: "1",
175
- accountId: 1,
176
- },
177
- user: [
178
- { id: 2, role: "ADMIN", accountId: 1 }
179
- ]
180
- });
181
- // TODO: Check output
182
- const answer = await client.account.update({
183
- data: {
184
- users: {
185
- update: [{
186
- data: {
187
- role: "USER"
188
- },
189
- where: {
190
- id: 2,
191
- }
192
- }]
193
- }
194
- },
195
- where: {
196
- id: 1
197
- },
198
- include: {
199
- users: true
200
- }
201
- });
202
- expect(answer).toEqual({
203
- id: 1,
204
- users: [{
205
- id: 2,
206
- accountId: 1,
207
- role: "USER"
208
- }]
209
- });
210
- });
211
- test('update: update one-to-one', async () => {
212
- const client = await (0, __1.default)({
213
- account: [
214
- { id: 1, name: "A" }
215
- ],
216
- stripe: [{
217
- id: 2,
218
- accountId: 1,
219
- }],
220
- });
221
- // TODO: Check output
222
- const answer = await client.stripe.update({
223
- data: {
224
- account: {
225
- update: {
226
- name: "B"
227
- },
228
- }
229
- },
230
- where: {
231
- id: 2
232
- },
233
- include: {
234
- account: true
235
- }
236
- });
237
- expect(answer).toEqual({
238
- id: 2,
239
- accountId: 1,
240
- account: {
241
- id: 1,
242
- name: "B"
243
- }
244
- });
245
- });
246
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,165 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- const src_1 = __importDefault(require("../src"));
8
- // TODO:
9
- // OR
10
- // Pagination
11
- // equals?: string | null
12
- // not?: string | StringFilter | null
13
- // in?: Enumerable<string> | null
14
- // notIn?: Enumerable<string> | null
15
- // every?: PostWhereInput | null
16
- // some?: PostWhereInput | null
17
- // none?: PostWhereInput | null
18
- // connect & create subitems
19
- // OrderBy
20
- describe('PrismaClient where', () => {
21
- const date1 = new Date(2020, 1, 1);
22
- const date2 = new Date(2020, 1, 2);
23
- const data = {
24
- user: [
25
- {
26
- id: 1,
27
- name: 'Henk',
28
- accountId: 1,
29
- },
30
- {
31
- id: 2,
32
- name: 'Dirk',
33
- accountId: 2,
34
- },
35
- ],
36
- account: [
37
- {
38
- id: 1,
39
- name: 'Piet',
40
- date: date1,
41
- },
42
- {
43
- id: 2,
44
- name: 'Dirk',
45
- date: date2,
46
- },
47
- {
48
- id: 3,
49
- name: 'Sjors',
50
- date: date2,
51
- },
52
- ],
53
- };
54
- test('multiple', async () => {
55
- const client = await (0, src_1.default)(data);
56
- const account = await client.account.findMany({
57
- where: {
58
- date: { lte: date1 },
59
- name: 'Dirk'
60
- },
61
- });
62
- expect(account).not.toEqual([data.account[0]]);
63
- });
64
- test('startsWith', async () => {
65
- const client = await (0, src_1.default)(data);
66
- const account = await client.account.findMany({
67
- where: {
68
- name: { startsWith: 'Di' },
69
- },
70
- });
71
- expect(account).toEqual([data.account[1]]);
72
- });
73
- test('endsWith', async () => {
74
- const client = await (0, src_1.default)(data);
75
- const account = await client.account.findMany({
76
- where: {
77
- name: { endsWith: 'rk' },
78
- },
79
- });
80
- expect(account).toEqual([data.account[1]]);
81
- });
82
- test('contains', async () => {
83
- const client = await (0, src_1.default)(data);
84
- const account = await client.account.findMany({
85
- where: {
86
- name: { contains: 'ir' },
87
- },
88
- });
89
- expect(account).toEqual([data.account[1]]);
90
- });
91
- test('equals', async () => {
92
- const client = await (0, src_1.default)(data);
93
- const account = await client.account.findMany({
94
- where: {
95
- name: { equals: 'Dirk' },
96
- },
97
- });
98
- expect(account).toEqual([data.account[1]]);
99
- });
100
- test('gt', async () => {
101
- const client = await (0, src_1.default)(data);
102
- const account = await client.account.findMany({
103
- where: {
104
- id: { gt: 1 },
105
- },
106
- });
107
- expect(account).toEqual([data.account[1], data.account[2]]);
108
- });
109
- test('gte', async () => {
110
- const client = await (0, src_1.default)(data);
111
- const account = await client.account.findMany({
112
- where: {
113
- id: { gte: 1 },
114
- },
115
- });
116
- expect(account).toEqual(data.account);
117
- });
118
- test('lt', async () => {
119
- const client = await (0, src_1.default)(data);
120
- const account = await client.account.findMany({
121
- where: {
122
- id: { lt: 2 },
123
- },
124
- });
125
- expect(account).toEqual([data.account[0]]);
126
- });
127
- test('lte', async () => {
128
- const client = await (0, src_1.default)(data);
129
- const account = await client.account.findMany({
130
- where: {
131
- id: { lte: 2 },
132
- },
133
- });
134
- expect(account).toEqual([data.account[0], data.account[1]]);
135
- });
136
- test('in', async () => {
137
- const client = await (0, src_1.default)(data);
138
- const account = await client.account.findMany({
139
- where: {
140
- name: { in: ['Piet', 'Sjors'] },
141
- },
142
- });
143
- expect(account).toEqual([data.account[0], data.account[2]]);
144
- });
145
- test('Deep', async () => {
146
- const client = await (0, src_1.default)(data);
147
- const account = await client.user.findMany({
148
- where: {
149
- account: {
150
- name: 'Dirk',
151
- },
152
- },
153
- });
154
- expect(account.length).toEqual(1);
155
- });
156
- test('date', async () => {
157
- const client = await (0, src_1.default)(data);
158
- const accounts = await client.account.findMany({
159
- where: {
160
- date: new Date(date1.toDateString()),
161
- },
162
- });
163
- expect(accounts).toEqual([data.account[0]]);
164
- });
165
- });
@@ -1,14 +0,0 @@
1
- declare type UnwrapPromise<P extends any> = P extends Promise<infer R> ? R : P;
2
- declare type PrismaDelegate = {
3
- findUnique: (...args: Array<any>) => Promise<any>;
4
- };
5
- declare type IsTable<S> = S extends `\$${infer fnc}` ? never : S;
6
- declare type IsString<S extends any> = S extends string ? S : never;
7
- declare type PrismaList<P extends {
8
- [key: string]: any;
9
- }, K extends string> = P[K] extends PrismaDelegate ? Array<Partial<UnwrapPromise<ReturnType<P[K]["findUnique"]>>>> : never;
10
- export declare type PrismaMockData<P> = Partial<{
11
- [key in IsTable<Uncapitalize<IsString<keyof P>>>]: PrismaList<P, key>;
12
- }>;
13
- declare const createPrismaMock: <P>(data?: Partial<{ [key in IsTable<Uncapitalize<IsString<keyof P>>>]: PrismaList<P, key>; }>, pathToSchema?: string, client?: { [K in keyof P]: P[K] extends (...args: infer A) => infer B ? import("jest-mock-extended").CalledWithMock<B, A> : import("jest-mock-extended").DeepMockProxy<P[K]>; } & P) => Promise<P>;
14
- export default createPrismaMock;
package/lib/src/index.js DELETED
@@ -1,374 +0,0 @@
1
- "use strict";
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- const sdk_1 = require("@prisma/sdk");
18
- const jest_mock_extended_1 = require("jest-mock-extended");
19
- const path_1 = __importDefault(require("path"));
20
- // TODO:
21
- // - groupBy
22
- let cachedSchema;
23
- // type Key = Uncapitalize<ModelName>
24
- const createPrismaMock = async (data = {}, pathToSchema, client = (0, jest_mock_extended_1.mockDeep)()) => {
25
- const getCamelCase = (name) => {
26
- return name.substr(0, 1).toLowerCase() + name.substr(1);
27
- };
28
- const shallowCompare = (a, b) => {
29
- for (let key in a) {
30
- if (a[key] !== b[key])
31
- return false;
32
- }
33
- return true;
34
- };
35
- const checkIds = (model, data) => {
36
- var _a;
37
- const c = getCamelCase(model.name);
38
- const idFields = model.idFields || ((_a = model.primaryKey) === null || _a === void 0 ? void 0 : _a.fields);
39
- // console.log("model.name", model.name)
40
- if ((idFields === null || idFields === void 0 ? void 0 : idFields.length) > 1) {
41
- const id = idFields.join('_');
42
- data = Object.assign(Object.assign({}, data), { [c]: data[c].map(item => {
43
- return Object.assign(Object.assign({}, item), { [id]: idFields.reduce((prev, field) => {
44
- return Object.assign(Object.assign({}, prev), { [field]: item[field] });
45
- }, {}) });
46
- }) });
47
- }
48
- return data;
49
- };
50
- const getFieldRelationshipWhere = (item, field) => ({
51
- [field.relationToFields[0]]: item[field.relationFromFields[0]],
52
- });
53
- const getJoinField = (field) => {
54
- const joinmodel = cachedSchema.datamodel.models.find(model => {
55
- return model.name === field.type;
56
- });
57
- const joinfield = joinmodel.fields.find(f => {
58
- return f.relationName === field.relationName;
59
- });
60
- return joinfield;
61
- };
62
- if (!cachedSchema) {
63
- const schemaPath = path_1.default.resolve(process.cwd(), 'prisma/schema.prisma');
64
- var pathToModule = pathToSchema || require.resolve(schemaPath);
65
- const datamodel = (0, sdk_1.getSchemaSync)(pathToModule);
66
- cachedSchema = await (0, sdk_1.getDMMF)({
67
- datamodel,
68
- });
69
- }
70
- // @ts-ignore
71
- client["$transaction"].mockImplementation((actions) => {
72
- return Promise.all(actions);
73
- });
74
- const Delegate = (prop, model) => {
75
- const nestedUpdate = (args, isCreating) => {
76
- let d = args.data;
77
- // Get field schema for default values
78
- const model = cachedSchema.datamodel.models.find(model => {
79
- return getCamelCase(model.name) === prop;
80
- });
81
- model.fields.forEach(field => {
82
- if (d[field.name] && field.kind === 'object') {
83
- const c = d[field.name];
84
- if (c.connect) {
85
- const _a = d, _b = field.name, connect = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
86
- d = Object.assign(Object.assign({}, rest), { [field.relationFromFields[0]]: connect.connect[field.relationToFields[0]] });
87
- }
88
- if (c.create || c.createMany) {
89
- const _c = d, _d = field.name, create = _c[_d], rest = __rest(_c, [typeof _d === "symbol" ? _d : _d + ""]);
90
- d = rest;
91
- // @ts-ignore
92
- const name = getCamelCase(field.type);
93
- const delegate = Delegate(name, model);
94
- const joinfield = getJoinField(field);
95
- if (field.relationFromFields.length > 0) {
96
- const item = delegate.create({
97
- data: create.create
98
- });
99
- d = Object.assign(Object.assign({}, rest), { [field.relationFromFields[0]]: item[field.relationToFields[0]] });
100
- }
101
- else {
102
- const map = (val) => (Object.assign(Object.assign({}, val), { [joinfield.name]: {
103
- connect: joinfield.relationToFields.reduce((prev, cur, index) => {
104
- let val = d[cur];
105
- if (!isCreating && !val) {
106
- val = findOne(args)[cur];
107
- }
108
- return Object.assign(Object.assign({}, prev), { [cur]: val });
109
- }, {}),
110
- } }));
111
- if (c.createMany) {
112
- delegate.createMany(Object.assign(Object.assign({}, c.createMany), { data: c.createMany.data.map(map) }));
113
- }
114
- else {
115
- delegate.create(Object.assign(Object.assign({}, create.create), { data: map(create.create) }));
116
- }
117
- }
118
- }
119
- if (c.update || c.updateMany) {
120
- const name = getCamelCase(field.type);
121
- const delegate = Delegate(name, model);
122
- if (c.updateMany) {
123
- if (Array.isArray(c.updateMany)) {
124
- c.updateMany.forEach(updateMany => {
125
- delegate.updateMany(updateMany);
126
- });
127
- }
128
- else {
129
- delegate.updateMany(c.updateMany);
130
- }
131
- }
132
- else {
133
- if (Array.isArray(c.update)) {
134
- c.update.forEach(update => {
135
- delegate.update(update);
136
- });
137
- }
138
- else {
139
- const item = findOne(args);
140
- delegate.update({ data: c.update, where: getFieldRelationshipWhere(item, field) });
141
- }
142
- }
143
- }
144
- }
145
- if (isCreating && !d[field.name] && field.default) {
146
- if (typeof field.default === 'object') {
147
- if (field.default.name === 'autoincrement') {
148
- let m = 1;
149
- data[prop].forEach(item => {
150
- m = Math.max(m, item[field.name]);
151
- });
152
- d = Object.assign(Object.assign({}, d), { [field.name]: m + 1 });
153
- }
154
- }
155
- else {
156
- d = Object.assign(Object.assign({}, d), { [field.name]: field.default });
157
- }
158
- }
159
- // return field.name === key
160
- });
161
- return d;
162
- };
163
- const matchFnc = args => item => {
164
- var _a;
165
- if (args === null || args === void 0 ? void 0 : args.where) {
166
- for (let child in args === null || args === void 0 ? void 0 : args.where) {
167
- const val = item[child];
168
- const filter = args.where[child];
169
- if (filter instanceof Date) {
170
- if (val === undefined) {
171
- return false;
172
- }
173
- if (!(val instanceof Date) || val.getTime() !== filter.getTime()) {
174
- return false;
175
- }
176
- }
177
- else {
178
- if (typeof filter === 'object') {
179
- const info = model.fields.find(field => field.name === child);
180
- if (info === null || info === void 0 ? void 0 : info.relationName) {
181
- const childName = getCamelCase(info.type);
182
- const res = data[childName].filter(matchFnc({
183
- where: Object.assign(Object.assign({}, filter), getFieldRelationshipWhere(item, info)),
184
- }));
185
- return res.length > 0;
186
- }
187
- const idFields = model.idFields || ((_a = model.primaryKey) === null || _a === void 0 ? void 0 : _a.fields);
188
- if ((idFields === null || idFields === void 0 ? void 0 : idFields.length) > 1) {
189
- if (child === idFields.join('_')) {
190
- return shallowCompare(val, filter);
191
- }
192
- }
193
- if (val === undefined) {
194
- return false;
195
- }
196
- let match = true;
197
- if ('equals' in filter && match) {
198
- match = filter.equals === val;
199
- }
200
- if ('startsWith' in filter && match) {
201
- match = val.indexOf(filter.startsWith) === 0;
202
- }
203
- if ('endsWith' in filter && match) {
204
- match =
205
- val.indexOf(filter.endsWith) ===
206
- val.length - filter.endsWith.length;
207
- }
208
- if ('contains' in filter && match) {
209
- match = val.indexOf(filter.contains) > -1;
210
- }
211
- if ('gt' in filter && match) {
212
- match = val > filter.gt;
213
- }
214
- if ('gte' in filter && match) {
215
- match = val >= filter.gte;
216
- }
217
- if ('lt' in filter && match) {
218
- match = val < filter.lt;
219
- }
220
- if ('lte' in filter && match) {
221
- match = val <= filter.lte;
222
- }
223
- if ('in' in filter && match) {
224
- match = filter.in.includes(val);
225
- }
226
- if (!match)
227
- return false;
228
- }
229
- else if (val !== filter) {
230
- return false;
231
- }
232
- }
233
- }
234
- }
235
- return true;
236
- };
237
- const findOne = args => {
238
- if (!data[prop])
239
- throw new Error(`${prop} not found in data`);
240
- return includes(args)(data[prop].find(matchFnc(args)));
241
- };
242
- const findMany = args => {
243
- const res = data[prop].filter(matchFnc(args)).map(includes(args));
244
- if (args === null || args === void 0 ? void 0 : args.distinct) {
245
- let values = {};
246
- return res.filter(item => {
247
- let shouldInclude = true;
248
- args.distinct.forEach(key => {
249
- const vals = values[key] || [];
250
- if (vals.includes(item[key])) {
251
- shouldInclude = false;
252
- }
253
- else {
254
- vals.push(item[key]);
255
- values[key] = vals;
256
- }
257
- });
258
- return shouldInclude;
259
- });
260
- }
261
- return res;
262
- };
263
- const findFirst = args => {
264
- const item = data[prop].find(matchFnc(args));
265
- if (item)
266
- return includes(args)(item);
267
- return null;
268
- };
269
- const updateMany = args => {
270
- // if (!Array.isArray(data[prop])) {
271
- // throw new Error(`${prop} not found in data`)
272
- // }
273
- const newItems = data[prop].map(e => {
274
- if (matchFnc(args)(e)) {
275
- let data = nestedUpdate(args, false);
276
- return Object.assign(Object.assign({}, e), data);
277
- }
278
- return e;
279
- });
280
- data = Object.assign(Object.assign({}, data), { [prop]: newItems });
281
- return data;
282
- };
283
- const create = args => {
284
- const d = nestedUpdate(args, true);
285
- data = Object.assign(Object.assign({}, data), { [prop]: [...data[prop], d] });
286
- data = checkIds(model, data);
287
- return findOne(Object.assign({ where: { id: d.id } }, args));
288
- };
289
- const deleteMany = args => {
290
- data = Object.assign(Object.assign({}, data), { [prop]: data[prop].filter(e => !matchFnc(args)(e)) });
291
- };
292
- const includes = args => item => {
293
- if (!(args === null || args === void 0 ? void 0 : args.include) || !item)
294
- return item;
295
- let newItem = item;
296
- const keys = Object.keys(args.include);
297
- keys.forEach(key => {
298
- // Get field schema for relation info
299
- const model = cachedSchema.datamodel.models.find(model => {
300
- return getCamelCase(model.name) === prop;
301
- });
302
- const schema = model.fields.find(field => {
303
- return field.name === key;
304
- });
305
- // Get delegate for relation
306
- const delegate = Delegate(getCamelCase(schema.type), model);
307
- // Construct arg for relation query
308
- let subArgs = args.include[key] === true ? {} : args.include[key];
309
- subArgs = Object.assign(Object.assign({}, subArgs), { where: Object.assign(Object.assign({}, subArgs.where), getFieldRelationshipWhere(item, schema)) });
310
- if (schema.isList) {
311
- // Add relation
312
- newItem = Object.assign(Object.assign({}, newItem), { [key]: delegate.findMany(subArgs) });
313
- }
314
- else {
315
- newItem = Object.assign(Object.assign({}, newItem), { [key]: delegate.findUnique(subArgs) });
316
- }
317
- });
318
- return newItem;
319
- };
320
- return {
321
- findOne,
322
- findUnique: findOne,
323
- findMany,
324
- findFirst,
325
- create,
326
- createMany: (args) => {
327
- args.data.forEach((data) => {
328
- create(Object.assign(Object.assign({}, args), { data }));
329
- });
330
- return findMany(args);
331
- },
332
- delete: deleteMany,
333
- update: (args) => {
334
- updateMany(args);
335
- return findOne(args);
336
- },
337
- deleteMany,
338
- updateMany: (args) => {
339
- updateMany(args);
340
- return findMany(args);
341
- },
342
- upsert(args) {
343
- const res = findOne(args);
344
- if (res) {
345
- updateMany(Object.assign(Object.assign({}, args), { data: args.update }));
346
- }
347
- else {
348
- create(Object.assign(Object.assign({}, args), { data: args.create }));
349
- }
350
- },
351
- count(args) {
352
- const res = findMany(args);
353
- return res.length;
354
- },
355
- };
356
- };
357
- cachedSchema.datamodel.models.forEach(model => {
358
- if (!model)
359
- return;
360
- const c = getCamelCase(model.name);
361
- if (!data[c]) {
362
- data = Object.assign(Object.assign({}, (data || {})), { [c]: [] });
363
- }
364
- data = checkIds(model, data);
365
- const objs = Delegate(c, model);
366
- Object.keys(objs).forEach(fncName => {
367
- client[c][fncName].mockImplementation(async (...params) => {
368
- return objs[fncName](...params);
369
- });
370
- });
371
- });
372
- return client;
373
- };
374
- exports.default = createPrismaMock;