forked from arthurfiorette/prisma-json-types-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace-object.ts
More file actions
74 lines (63 loc) · 2.37 KB
/
replace-object.ts
File metadata and controls
74 lines (63 loc) · 2.37 KB
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
import ts from 'typescript';
import type { PrismaEntity } from '../helpers/dmmf';
import { findNewSignature } from '../helpers/find-signature';
import { parseTypeSyntax } from '../helpers/type-parser';
import type { PrismaJsonTypesGeneratorConfig } from '../util/config';
import { createType } from '../util/create-signature';
import type { DeclarationWriter } from '../util/declaration-writer';
import { PrismaJsonTypesGeneratorError } from '../util/error';
/** Tries to replace every property of an object */
export function replaceObject(
object: ts.TypeLiteralNode,
writer: DeclarationWriter,
model: PrismaEntity,
config: PrismaJsonTypesGeneratorConfig
) {
for (const field of model.fields) {
const parsed = parseTypeSyntax(field.documentation);
// Not annotated with JSON comment and we should let it be any
if (!parsed && config.allowAny) {
continue;
}
for (const member of object.members) {
const memberName = member.name?.getText();
if (
// Not sure when a object member cannot be a PropertySignature,
// here to avoid errors
member.kind !== ts.SyntaxKind.PropertySignature ||
// The field name does not match the member name
field.name !== memberName
) {
continue;
}
// the original `field: Type`
const signature = (member as ts.PropertySignature).type;
if (!signature) {
throw new PrismaJsonTypesGeneratorError('Could not find signature type', {
type: field.name
});
}
const newType = createType(field.documentation, config);
// If the created type was defaulted to unknown because no other type annotation was provided
const defaultedToUnknown = newType === 'unknown';
const newSignature = findNewSignature(
signature.getText(),
// Updates the typename according to the config
newType,
model.name,
field.name,
// We must ignore not found errors when no typename was found but we still
// are replacing because of allowAny = false
!defaultedToUnknown,
!defaultedToUnknown,
writer.multifile ? 'PJTG.' : ''
);
// This type should be ignored by the generator
if (!newSignature) {
continue;
}
// Replaces the signature with the new one
writer.replace(signature.pos, signature.end, newSignature);
}
}
}