|
1
|
import type { PropertyType } from "@medusajs/types" |
|
2
|
import { DmlEntity } from "../entity" |
|
3
|
import { getForeignKey } from "./entity-builder" |
|
4
|
import { parseEntityName } from "./entity-builder/parse-entity-name" |
|
5
|
import { getGraphQLAttributeFromDMLPropety } from "./graphql-builder/get-attribute" |
|
6
|
import { setGraphQLRelationship } from "./graphql-builder/set-relationship" |
|
7
|
|
|
8
|
export function generateGraphQLFromEntity<T extends DmlEntity<any, any>>( |
|
9
|
entity: T |
|
10
|
): string { |
|
11
|
const { schema } = entity.parse() |
|
12
|
const { modelName } = parseEntityName(entity) |
|
13
|
|
|
14
|
let extra: string[] = [] |
|
15
|
let gqlSchema: string[] = [] |
|
16
|
|
|
17
|
Object.entries(schema).forEach(([name, property]) => { |
|
18
|
const field = property.parse(name) |
|
19
|
|
|
20
|
if ("fieldName" in field) { |
|
21
|
const prop = getGraphQLAttributeFromDMLPropety( |
|
22
|
modelName, |
|
23
|
name, |
|
24
|
property as PropertyType<any> |
|
25
|
) |
|
26
|
|
|
27
|
if (prop.enum) { |
|
28
|
extra.push(prop.enum) |
|
29
|
} |
|
30
|
|
|
31
|
gqlSchema.push(`${prop.attribute}`) |
|
32
|
} else { |
|
33
|
if (["belongsTo", "hasOneWithFK"].includes(field.type)) { |
|
34
|
const foreignKeyName = getForeignKey(field) |
|
35
|
const fkProp = getGraphQLAttributeFromDMLPropety( |
|
36
|
modelName, |
|
37
|
field.name, |
|
38
|
{ |
|
39
|
$dataType: "", |
|
40
|
parse() { |
|
41
|
return { |
|
42
|
fieldName: foreignKeyName, |
|
43
|
computed: false, |
|
44
|
dataType: { name: "text" as const }, |
|
45
|
nullable: field.nullable || false, |
|
46
|
indexes: [], |
|
47
|
relationships: [], |
|
48
|
} |
|
49
|
}, |
|
50
|
} |
|
51
|
) |
|
52
|
gqlSchema.push(`${fkProp.attribute}`) |
|
53
|
} |
|
54
|
|
|
55
|
const prop = setGraphQLRelationship(modelName, field) |
|
56
|
if (prop.extra) { |
|
57
|
extra.push(prop.extra) |
|
58
|
} |
|
59
|
|
|
60
|
gqlSchema.push(`${prop.attribute}`) |
|
61
|
} |
|
62
|
}) |
|
63
|
|
|
64
|
return ` |
|
65
|
${extra.join("\n")} |
|
66
|
type ${modelName} { |
|
67
|
${gqlSchema.join("\n")} |
|
68
|
} |
|
69
|
` |
|
70
|
} |
|
71
|
|
|
72
|
/** |
|
73
|
* Takes a DML entity and returns a GraphQL schema string. |
|
74
|
* @param entity |
|
75
|
*/ |
|
76
|
export const toGraphQLSchema = <T extends any[]>(entities: T): string => { |
|
77
|
const gqlSchemas = entities.map((entity) => { |
|
78
|
if (DmlEntity.isDmlEntity(entity)) { |
|
79
|
return generateGraphQLFromEntity(entity) |
|
80
|
} |
|
81
|
|
|
82
|
return entity |
|
83
|
}) |
|
84
|
|
|
85
|
const defaultMedusaSchema = |
|
86
|
gqlSchemas.length > 0 |
|
87
|
? ` |
|
88
|
scalar DateTime |
|
89
|
scalar JSON |
|
90
|
directive @enumValue(value: String) on ENUM_VALUE |
|
91
|
` |
|
92
|
: "" |
|
93
|
|
|
94
|
return defaultMedusaSchema + gqlSchemas.join("\n") |
|
95
|
} |