forked from albingroen/prismabuilder.io-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prisma.ts
83 lines (71 loc) · 2.21 KB
/
prisma.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
const parseRelationship = (relation: any) => {
if (!relation) {
return "";
}
const parseRelationshipArg = (fields: any[]) => {
return "[" + fields.join(",") + "]";
};
const relationName = relation.name ? `"${relation.name}"` : "";
const prependRelationFields = relation.name ? ", " : "";
const relationFields = relation.fields
? `${prependRelationFields}fields: ${parseRelationshipArg(
relation.fields
)}, `
: "";
const relationReferences = relation.references
? `references: ${parseRelationshipArg(relation.references)}`
: "";
return ` @relation(${relationName}${relationFields}${relationReferences})`;
};
const parseModelFields = (fields: any[]) => {
return fields.map(
({
name,
type,
list,
required,
isId,
isUpdatedAt,
relation,
default: defaultValue,
unique: isUnique,
}) => {
const array = list ? "[]" : "";
const optional = list ? "" : required ? "" : "?";
const id = isId ? " @id" : "";
const updatedAt = isUpdatedAt ? " @updatedAt" : "";
const unique = isUnique ? " @unique" : "";
const default_value = defaultValue ? ` @default(${defaultValue})` : "";
const relationship = parseRelationship(relation);
return ` ${name} ${type}${array}${optional}${id}${unique}${relationship}${default_value}${updatedAt}`;
}
);
};
const parseModels = (models: any[]) => {
return models.reduce((a, { name, fields }) => {
return [...a, `model ${name} {`, ...parseModelFields(fields), "}", "", ""];
}, []);
};
const parseEnumFields = (fields: any[]) => {
return fields.map((field) => ` ${field}`);
};
const parseEnums = (enums: any[]) => {
return enums.reduce((a, { name, fields }) => {
return [...a, `enum ${name} {`, ...parseEnumFields(fields), "}"];
}, []);
};
export const jsonToPrismaSchema = (jsonSchema: any) => {
const prismaSchema = Object.entries(jsonSchema).reduce(
(a: any, [type, values]: [any, any]) => {
if (type === "models") {
return [...a, ...parseModels(values)];
}
if (type === "enums") {
return [...a, ...parseEnums(values)];
}
return a;
},
[]
);
return prismaSchema.join("\n");
};