forked from unlight/prisma-nestjs-graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.spec.ts
2357 lines (2074 loc) · 75.5 KB
/
generate.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable regexp/strict */
import expect from 'expect';
import JSON5 from 'json5';
import { trim } from 'lodash';
import {
ClassDeclaration,
EnumDeclarationStructure,
ImportDeclarationStructure,
ImportSpecifierStructure,
Project,
PropertyDeclaration,
PropertyDeclarationStructure,
SourceFile,
} from 'ts-morph';
import { EventArguments } from '../types';
import { getFieldOptions, getPropertyStructure } from './helpers';
import { testGenerate } from './test-generate';
let sourceFile: SourceFile;
let sourceText: string;
let project: Project;
let propertyStructure: PropertyDeclarationStructure;
let imports: { name: string; specifier: string }[];
let classFile: ClassDeclaration;
let sourceFiles: SourceFile[];
let importDeclarations: ImportDeclarationStructure[] = [];
const p = (name: string) => getPropertyStructure(sourceFile, name);
const d = (name: string) => getPropertyStructure(sourceFile, name)?.decorators?.[0];
const f = (name: string) =>
getPropertyStructure(sourceFile, name)?.decorators?.find(d => d.name === 'Field')
?.arguments;
const t = (name: string) => f(name)?.[0];
const setSourceFile = (name: string) => {
sourceFile = project.getSourceFileOrThrow(s => s.getFilePath().endsWith(name));
sourceText = sourceFile.getText();
classFile = sourceFile.getClass(() => true)!;
importDeclarations = sourceFile.getImportDeclarations().map(d => d.getStructure());
imports = importDeclarations.flatMap(d =>
(d.namedImports as ImportSpecifierStructure[]).map(x => ({
name: x.name,
specifier: d.moduleSpecifier,
})),
);
};
const objectTypeArguments = () =>
sourceFile
.getClass(() => true)
?.getDecorator('ObjectType')
?.getStructure().arguments;
describe('model with one id int', () => {
let id: PropertyDeclarationStructure;
before(async () => {
({ project, sourceFiles } = await testGenerate({
schema: `
/// User really
model User {
/// user id really
id Int @id @default(1)
}`,
}));
});
describe('model', () => {
before(() => setSourceFile('user.model.ts'));
it('class should be exported', () => {
const [classFile] = sourceFile.getClasses();
expect(classFile.isExported()).toBe(true);
});
it('argument decorated id', () => {
expect(t('id')).toEqual('() => ID');
});
it('should have import graphql type id', () => {
expect(imports).toContainEqual({
name: 'ID',
specifier: '@nestjs/graphql',
});
});
it('should have import field decorator', () => {
expect(imports).toContainEqual({
name: 'Field',
specifier: '@nestjs/graphql',
});
});
it('should have exclamation mark for non null id field', () => {
id = sourceFile
.getClass(() => true)
?.getProperty(p => p.getName() === 'id')
?.getStructure()!;
expect(id.hasExclamationToken).toEqual(true);
});
// it('', () => console.log(sourceFile.getText()));
it('default value', () => {
const argument = getFieldOptions(sourceFile, 'id');
expect(argument).toMatch(/nullable:\s*false/);
expect(argument).toMatch(/defaultValue:\s*1/);
expect(argument).not.toMatch(/description:\s*undefined/);
});
it('property description', () => {
const argument = getFieldOptions(sourceFile, 'id');
expect(argument).toMatch(/nullable:\s*false/);
expect(argument).toMatch(/description:\s*["']user id really["']/);
});
it('property description in jsdoc', () => {
const description = classFile
.getProperty('id')
?.getJsDocs()[0]
.getDescription();
expect(description).toEqual('user id really');
});
it('object type description', () => {
const decoratorArgument = classFile.getDecorators()[0].getStructure()
.arguments?.[0] as string | undefined;
expect(decoratorArgument).toMatch(/description:\s*["']User really["']/);
});
it('has js comment', () => {
expect(classFile.getJsDocs()[0].getDescription()).toEqual('User really');
});
it('has import objecttype', () => {
expect(imports).toContainEqual({
name: 'ObjectType',
specifier: '@nestjs/graphql',
});
});
});
describe('aggregate user output', () => {
before(() => {
setSourceFile('aggregate-user.output.ts');
});
// it('', () => console.log(sourceText));
it('class should be exported', () => {
const [classFile] = sourceFile.getClasses();
expect(classFile.isExported()).toBe(true);
});
it('contains decorator ObjectType', () => {
expect(imports).toContainEqual({
name: 'ObjectType',
specifier: '@nestjs/graphql',
});
});
it('count', () => {
const structure = sourceFile
.getClass(() => true)
?.getProperty(p => p.getName() === '_count')
?.getStructure();
expect(structure?.type).toEqual('UserCountAggregate');
expect(structure?.hasQuestionToken).toEqual(true);
});
});
describe('user count aggregate (usercountaggregate)', () => {
before(() => {
setSourceFile('user-count-aggregate.output.ts');
propertyStructure = sourceFile
.getClass(() => true)
?.getProperty(p => p.getName() === 'id')
?.getStructure()!;
});
// it('', () => console.log(sourceFile.getText()));
it('id property should be Int/number', () => {
expect(propertyStructure.type).toEqual('number');
expect(d('id')?.arguments?.[0]).toEqual('() => Int');
});
it('should be not null', () => {
expect(propertyStructure.hasQuestionToken).toEqual(false);
});
it('should have import graphql type int', () => {
expect(imports).toContainEqual({
name: 'Int',
specifier: '@nestjs/graphql',
});
});
});
describe('where input', () => {
before(() => {
sourceFile = project.getSourceFile(s =>
s.getFilePath().endsWith('user-where.input.ts'),
)!;
});
// it('', () => console.log(sourceFile.getText()));
it('should have id property', () => {
id = getPropertyStructure(sourceFile, 'id')!;
expect(id).toEqual(expect.objectContaining({ name: 'id' }));
});
it('should have type IntFilter', () => {
id = getPropertyStructure(sourceFile, 'id')!;
expect(id.type).toEqual('IntFilter');
});
it('field decorator returns IntFilter', () => {
const argument = t('id');
expect(argument).toEqual('() => IntFilter');
});
it('field decorator IntFilter nullable', () => {
const argument = getFieldOptions(sourceFile, 'id');
expect(argument).toMatch(/nullable:\s*true/);
});
it('property AND has one type', () => {
expect(getPropertyStructure(sourceFile, 'AND')?.type).toEqual(
'Array<UserWhereInput>',
);
});
});
describe('aggregate user args', () => {
before(() => {
setSourceFile('user-aggregate.args.ts');
classFile = sourceFile.getClass(() => true)!;
});
// it('', () => console.log(sourceFile.getText()));
it('decorator name args', () => {
const decorator = classFile.getDecorator('ArgsType');
expect(decorator).toBeTruthy();
});
it('no duplicated properties', () => {
const names = sourceFile
.getClass(() => true)
?.getProperties()
.map(p => p.getName())!;
expect([...new Set(names).values()]).toHaveLength(names.length);
});
it('count', () => {
expect(p('_count')?.type).toEqual('UserCountAggregateInput');
});
it('sum', () => {
expect(p('_sum')?.type).toEqual('UserSumAggregateInput');
});
it('min', () => {
expect(p('_min')?.type).toEqual('UserMinAggregateInput');
});
it('max', () => {
expect(p('_max')?.type).toEqual('UserMaxAggregateInput');
});
});
describe('user count aggregate input', () => {
let id: PropertyDeclarationStructure;
before(() => {
setSourceFile('user-count-aggregate.input.ts');
id = getPropertyStructure(sourceFile, 'id')!;
});
// it('', () => console.log(sourceFile.getText()));
it('property id should have true type', () => {
expect(id.type).toEqual('true');
});
it('nullable', () => {
expect(id.hasQuestionToken).toEqual(true);
});
it('decorated field type should be boolean', () => {
const argument = t('id');
expect(argument).toEqual('() => Boolean');
});
});
it('rename to user-group-by args', () => {
setSourceFile('user-group-by.args.ts');
expect(sourceFile.getClass(() => true)?.getName()).toEqual('UserGroupByArgs');
});
it('rename to user aggregateargs', () => {
setSourceFile('user-aggregate.args.ts');
expect(sourceFile.getClass(() => true)?.getName()).toEqual('UserAggregateArgs');
});
});
describe('duplicated', () => {
it('duplicated fields in exising file', async () => {
({ project, sourceFiles } = await testGenerate({
schema: `
model User {
id Int @id
}
`,
createSouceFile: {
type: 'input',
name: 'UserCreateInput',
text: `
import { Int } from '@nestjs/graphql';
@InputType()
export class UserCreateInput {
@Field(() => String, {
nullable: true,
})
id?: string;
`,
},
}));
setSourceFile('/user-create.input.ts');
const classFile = sourceFile.getClass(() => true)!;
const names = classFile.getProperties().map(p => p.getName());
expect(names).toStrictEqual(['id']);
});
it('duplicated import decorators', async () => {
({ project, sourceFiles } = await testGenerate({
schema: `
model User {
id Int @id
xl Int
xs Int
}
`,
createSouceFile: {
type: 'model',
name: 'User',
text: `
import { Field, ObjectType } from '@nestjs/graphql';
import { Int, ID } from '@nestjs/graphql';
@ObjectType()
export class User {
@Field(() => ID) id: number;
@Field(() => Int) xl: number;
@Field(() => Int) xs: number;
`,
},
}));
setSourceFile('user.model.ts');
expect(imports.filter(x => x.name === 'Field')).toHaveLength(1);
expect(imports.filter(x => x.name === 'ObjectType')).toHaveLength(1);
});
});
describe('one model with scalar types', () => {
before(async () => {
({ project, sourceFiles } = await testGenerate({
schema: `model User {
id String @id
count Int
rating Float
born DateTime
humanoid Boolean
money Decimal
data Json
biggy BigInt
}`,
}));
// const filePaths = sourceFiles.map(s => s.getFilePath());
});
describe('user model', () => {
before(() => {
setSourceFile('user.model.ts');
});
describe('property types', () => {
it('boolean', () => {
expect(getPropertyStructure(sourceFile, 'humanoid')?.type).toEqual(
'boolean',
);
});
it('rating', () => {
expect(getPropertyStructure(sourceFile, 'rating')?.type).toEqual(
'number',
);
});
it('count', () => {
expect(getPropertyStructure(sourceFile, 'count')?.type).toEqual(
'number',
);
});
it('born', () => {
expect(getPropertyStructure(sourceFile, 'born')?.type).toEqual('Date');
});
it('big int', () => {
expect(p('biggy')?.type).toEqual('bigint');
});
it('money', () => {
expect(p('money')?.type).toEqual('any');
});
});
describe('json type', () => {
it('should import graphqljson', () => {
expect(imports).toContainEqual({
name: 'GraphQLJSON',
specifier: 'graphql-type-json',
});
});
it('field decorator should return custom graphqljson type', () => {
expect(t('data')).toEqual('() => GraphQLJSON');
});
});
});
describe('datetime filter', () => {
before(() => {
sourceFile = project.getSourceFile(s =>
s.getFilePath().endsWith('/date-time-filter.input.ts'),
)!;
});
// it('^\n', () => console.log(sourceFile.getText()));
it('equals field type Date', () => {
expect(t('equals')).toEqual('() => Date');
});
it('equals is optional', () => {
const structure = getPropertyStructure(sourceFile, 'equals');
expect(structure?.hasQuestionToken).toEqual(true);
expect(getFieldOptions(sourceFile, 'equals')).toMatch(/nullable:\s*true/);
});
it('not property should be object type', () => {
expect(t('not')).toContain('DateTimeFilter');
});
it('compatiblity datetime filter', () => {
const classFile = sourceFile.getClass('DateTimeFilter')!;
const fieldIn = classFile.getProperty('in')!;
expect(fieldIn.getStructure().type).toEqual('Array<Date> | Array<string>');
});
});
describe('user where input', () => {
before(() => {
setSourceFile('user-where.input.ts');
});
it('number should have int filter', () => {
const structure = getPropertyStructure(sourceFile, 'count');
expect(structure?.type).toEqual('IntFilter');
});
it('decorator argument int filter', () => {
const p = t('count');
expect(p).toEqual('() => IntFilter');
});
it('contains scalar filters', () => {
expect(imports).toContainEqual({
name: 'StringFilter',
specifier: '../prisma/string-filter.input',
});
expect(imports).toContainEqual({
name: 'IntFilter',
specifier: '../prisma/int-filter.input',
});
});
});
describe('string filter input', () => {
before(() => {
sourceFile = project.getSourceFile(s =>
s.getFilePath().endsWith('/string-filter.input.ts'),
)!;
});
// it('', () => console.log(sourceFile.getText()));
it('properties and types', () => {
const properties = sourceFile.getClass(() => true)?.getProperties();
const structure = (name: string) =>
properties?.find(x => x.getName() === name)?.getStructure();
expect(structure('equals')?.type).toEqual('string');
expect(structure('lt')?.type).toEqual('string');
expect(structure('lte')?.type).toEqual('string');
expect(structure('gt')?.type).toEqual('string');
expect(structure('gte')?.type).toEqual('string');
expect(structure('contains')?.type).toEqual('string');
expect(structure('startsWith')?.type).toEqual('string');
expect(structure('endsWith')?.type).toEqual('string');
expect(structure('in')?.type).toEqual('Array<string>');
expect(structure('notIn')?.type).toEqual('Array<string>');
});
});
describe('user create input', () => {
before(() => {
setSourceFile('/user-create.input.ts');
});
it('valid imports', () => {
expect(sourceText).not.toContain("import ';");
});
it('imports', () => {
expect(imports).toContainEqual({
name: 'InputType',
specifier: '@nestjs/graphql',
});
expect(imports).toContainEqual({
name: 'Int',
specifier: '@nestjs/graphql',
});
});
it('id field type is string', () => {
const id = t('id');
expect(id).toEqual('() => String');
});
it('float property', () => {
const property = getPropertyStructure(sourceFile, 'rating');
expect(property?.type).toEqual('number');
});
it('data property (json)', () => {
expect(t('data')).toEqual('() => GraphQLJSON');
});
it('native string should not be imported', () => {
expect(imports).not.toContainEqual(
expect.objectContaining({ name: 'String' }),
);
});
// it('', () => console.log(sourceFile.getText()));
});
describe('json filter', () => {
before(() => {
sourceFile = project.getSourceFile(s =>
s.getFilePath().endsWith('/json-filter.input.ts'),
)!;
});
it('not field should be json filter', () => {
const not = p('not');
expect(not?.type).toEqual('any');
});
it('field type should be GraphQLJSON', () => {
expect(t('not')).toEqual('() => GraphQLJSON');
});
// it('', () => console.log(sourceFile.getText()));
});
});
describe('model with scalar nullable types', () => {
before(async () => {
({ project, sourceFiles } = await testGenerate({
schema: `model User {
id String @id
count Int?
rating Float?
born DateTime?
humanoid Boolean?
money Decimal?
data Json?
biggy BigInt?
}`,
options: [`outputFilePattern = "{name}.{type}.ts"`],
}));
});
it('nullable json', () => {
setSourceFile('user-create.input.ts');
expect(p('data')?.type).toEqual('any');
});
});
describe('scalar list type', () => {
describe('general', () => {
before(async () => {
({ project, sourceFiles } = await testGenerate({
schema: `
model User {
id Int @id
permissions String[]
}`,
}));
});
it('smoke', () => {
expect(sourceFiles.length).toBeTruthy();
});
it('user create input', () => {
setSourceFile('user-create.input.ts');
expect(p('permissions')?.type).toEqual('UserCreatepermissionsInput');
expect(t('permissions')).toEqual('() => UserCreatepermissionsInput');
});
});
});
describe('nullish compatibility', () => {
before(async () => {
({ project, sourceFiles } = await testGenerate({
schema: `
model User {
id String @id
count Int?
rating Float?
born DateTime?
humanoid Boolean?
money Decimal?
data Json?
biggy BigInt?
role Role?
posts Post[]
profile Profile?
}
model Post {
id Int @id
User User? @relation(fields: [userId], references: [id])
userId String?
}
model Profile {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId String
dummy String?
}
enum Role {
USER
}
`,
options: [`outputFilePattern = "{name}.{type}.ts"`],
}));
setSourceFile('user.model.ts');
});
it('number', () => {
expect(p('count')?.type).toEqual('number | null');
expect(p('count')?.hasQuestionToken).toBe(false);
});
it('born', () => {
expect(p('born')?.type).toEqual('Date | null');
expect(p('born')?.hasQuestionToken).toBe(false);
});
it('money', () => {
expect(p('money')?.type).toEqual('any | null');
expect(p('money')?.hasQuestionToken).toBe(false);
expect(imports).toContainEqual({
name: 'GraphQLDecimal',
specifier: 'prisma-graphql-type-decimal',
});
});
it('data', () => {
expect(p('data')?.type).toEqual('any | null');
expect(imports).toContainEqual({
name: 'GraphQLJSON',
specifier: 'graphql-type-json',
});
});
describe('relation fields should hasQuestionToken (optional)', () => {
it('profile', () => {
expect(p('profile')?.hasQuestionToken).toBe(true);
});
it('posts', () => {
expect(p('posts')?.hasQuestionToken).toBe(true);
});
});
// it('', () => console.log(sourceFile.getText()));
});
describe('one model with enum', () => {
before(async () => {
({ project, sourceFiles } = await testGenerate({
schema: `
/// Role really
enum Role {
USER
ADMIN
}
model User {
id Int @id
role Role
permissions String[]
}`,
}));
});
describe('sort order enum', () => {
before(() => {
setSourceFile('sort-order.enum.ts');
});
it('should import registerEnumType', () => {
expect(sourceText).toContain(
`import { registerEnumType } from '@nestjs/graphql'`,
);
});
it('should register SortOrder', () => {
expect(sourceText).toContain(
`registerEnumType(SortOrder, { name: 'SortOrder', description: undefined })`,
);
});
describe('enum sort order', () => {
let structure: EnumDeclarationStructure;
before(() => {
structure = sourceFile.getEnum('SortOrder')?.getStructure()!;
});
it('should have asc value', () => {
expect(structure.members).toContainEqual(
expect.objectContaining({
name: 'asc',
initializer: '"asc"',
}),
);
});
it('should have desc value', () => {
expect(structure.members).toContainEqual(
expect.objectContaining({
name: 'desc',
initializer: '"desc"',
}),
);
});
});
});
describe('role enum', () => {
before(() => {
setSourceFile('role.enum.ts');
});
it('should contains import registerEnumType with name role', () => {
expect(sourceText).toContain(`registerEnumType(Role,`);
expect(sourceText).toContain(`name: 'Role'`);
});
it('should contains', () => {
expect(sourceText).toContain(`description: "Role really"`);
});
});
describe('model', () => {
before(() => {
setSourceFile('user.model.ts');
});
// it('', () => console.log('sourceText', sourceText));
it('should import Role as enum', () => {
expect(imports).toContainEqual({
name: 'Role',
specifier: '../prisma/role.enum',
});
});
it('role type should use typeof keyof trick', () => {
const role = p('role');
expect(role?.type).toEqual('keyof typeof Role');
});
});
});
describe('one model with self reference', () => {
before(async () => {
({ project, sourceFiles } = await testGenerate({
schema: `model User {
id Int @id
parentId Int
parent User @relation("UserToUser", fields: [parentId], references: [id])
user User[] @relation("UserToUser")
}`,
}));
});
describe('model', () => {
before(() => {
setSourceFile('user.model.ts');
});
// it('', () => console.log('sourceText', sourceText));
it('should not contain import to self file', () => {
expect(imports).not.toContainEqual(
expect.objectContaining({ name: 'User' }),
);
});
it('imports should contain user count', () => {
expect(imports).toContainEqual({
name: 'UserCount',
specifier: './user-count.output',
});
});
});
describe('user list relation filter', () => {
before(() => {
sourceFile = project.getSourceFile(s =>
s.getFilePath().endsWith('/user-list-relation-filter.input.ts'),
)!;
});
it('every', () => {
const structure = getPropertyStructure(sourceFile, 'every');
expect(structure?.type).toEqual('UserWhereInput');
});
it('some', () => {
const structure = getPropertyStructure(sourceFile, 'some');
expect(structure?.type).toEqual('UserWhereInput');
});
it('none', () => {
const structure = getPropertyStructure(sourceFile, 'none');
expect(structure?.type).toEqual('UserWhereInput');
});
});
});
describe('two models with id only and relation', () => {
before(async () => {
({ project, sourceFiles } = await testGenerate({
schema: `
model User {
id Int @id
posts Post[]
}
model Post {
id Int @id
User User? @relation(fields: [userId], references: [id])
userId Int?
}
`,
}));
});
describe('user model', () => {
before(() => {
sourceFile = project.getSourceFile(s =>
s.getFilePath().endsWith('/user.model.ts'),
)!;
});
it('posts property', () => {
const p = getPropertyStructure(sourceFile, 'posts');
expect(p?.type).toEqual('Array<Post>');
});
});
});
it('enum with exists source', async () => {
({ project, sourceFiles } = await testGenerate({
schema: `enum Role {
USER
}
model User {
id Int @id
role Role
}`,
createSouceFile: {
name: 'Role',
type: 'enum',
text: `
export enum Role { USER = "USER" }
registerEnumType(Role, { name: 'Role' })
`,
},
}));
sourceFile = project.getSourceFile(s => s.getFilePath().includes('role.enum.ts'))!;
sourceText = sourceFile.getText();
expect(sourceText.match(/registerEnumType/g)).toHaveLength(2);
expect(sourceText.match(/enum Role/g)).toHaveLength(1);
});
describe('model with one id string', () => {
const schema = `
model User {
id String @id
}
`;
it('extend', async () => {
({ project, sourceFiles } = await testGenerate({
schema,
createSouceFile: {
type: 'model',
name: 'User',
text: `@ObjectType() export class User {}`,
},
}));
sourceFile = project.getSourceFile(s =>
s.getFilePath().endsWith('user.model.ts'),
)!;
sourceText = sourceFile.getText();
expect(sourceText.match(/export class User/g)?.length).toEqual(1);
});
it('remove description', async () => {
({ project, sourceFiles } = await testGenerate({
schema,
createSouceFile: {
type: 'model',
name: 'User',
text: `@ObjectType({ description: 'user description' }) export class User {}`,
},
}));
setSourceFile('user.model.ts');
const objectType = classFile.getDecorator('ObjectType')?.getText();
expect(objectType).toEqual('@ObjectType()');
});
it('generated commented class if reexport found', async () => {
({ project, sourceFiles } = await testGenerate({
schema,
createSouceFile: {
type: 'model',
name: 'User',
text: `
export { User } from 'src/user/model'
export { User as UserModel } from 'src/user2/model'
`,
},
}));
setSourceFile('user.model.ts');
expect(sourceText).toContain(`export { User } from 'src/user/model'`);
expect(sourceText).toContain(`// export class User`);
});
it('no generate another commented class', async () => {
({ project, sourceFiles } = await testGenerate({
schema,
createSouceFile: {
type: 'model',
name: 'User',
text: `
export { User } from 'src/user/model'
// @ObjectType()
// export class User { }
`,
},
}));
setSourceFile('user.model.ts');
expect(sourceText.match(/export class User/g)).toHaveLength(1);
expect(sourceText).toContain('// export class User');
});
});
it('generator option outputFilePattern', async () => {
({ project, sourceFiles } = await testGenerate({
schema: `model User {
id Int @id
}`,
options: [`outputFilePattern = "data/{type}/{name}.ts"`],
}));
const filePaths = sourceFiles.map(s => String(s.getFilePath()));
expect(filePaths).toContainEqual(expect.stringContaining('/data/model/user.ts'));
});
it('several models', () => {
before(async () => {
({ project, sourceFiles } = await testGenerate({