1 import { RemoteJoinerQuery } from "@medusajs/types"
2 import {
3 ArgumentNode,
4 DirectiveNode,
5 DocumentNode,
6 FieldNode,
7 Kind,
8 OperationDefinitionNode,
9 SelectionSetNode,
10 ValueNode,
11 parse,
12 } from "graphql"
13
14 interface Argument {
15 name: string
16 value?: unknown
17 }
18
19 interface Directive {
20 name: string
21 args?: Argument[]
22 }
23
24 interface Entity {
25 property: string
26 fields: string[]
27 args?: Argument[]
28 directives?: { [field: string]: Directive[] }
29 }
30
31 /**
32 * Remote joiner graphql parser
33 */
34 export class GraphQLParser {
35 private ast: DocumentNode
36
37 constructor(input: string, private variables: Record<string, unknown> = {}) {
38 this.ast = parse(input)
39 this.variables = variables
40 }
41
42 private parseValueNode(valueNode: ValueNode): unknown {
43 const obj = {}
44
45 switch (valueNode.kind) {
46 case Kind.VARIABLE:
47 return this.variables ? this.variables[valueNode.name.value] : undefined
48 case Kind.INT:
49 return parseInt(valueNode.value, 10)
50 case Kind.FLOAT:
51 return parseFloat(valueNode.value)
52 case Kind.BOOLEAN:
53 return Boolean(valueNode.value)
54 case Kind.STRING:
55 case Kind.ENUM:
56 return valueNode.value
57 case Kind.NULL:
58 return null
59 case Kind.LIST:
60 return valueNode.values.map((v) => this.parseValueNode(v))
61 case Kind.OBJECT:
62 for (const field of valueNode.fields) {
63 obj[field.name.value] = this.parseValueNode(field.value)
64 }
65 return obj
66 default:
67 return undefined
68 }
69 }
70
71 private parseArguments(
72 args: readonly ArgumentNode[]
73 ): Argument[] | undefined {
74 if (!args.length) {
75 return
76 }
77
78 return args.map((arg) => {
79 const value = this.parseValueNode(arg.value)
80
81 return {
82 name: arg.name.value,
83 value: value,
84 }
85 })
86 }
87
88 private parseDirectives(directives: readonly DirectiveNode[]): Directive[] {
89 return directives.map((directive) => ({
90 name: directive.name.value,
91 args: this.parseArguments(directive.arguments || []),
92 }))
93 }
94
95 private createDirectivesMap(selectionSet: SelectionSetNode):
96 | {
97 [field: string]: Directive[]
98 }
99 | undefined {
100 const directivesMap: { [field: string]: Directive[] } = {}
101 let hasDirectives = false
102 selectionSet.selections.forEach((field) => {
103 const fieldName = (field as FieldNode).name.value
104 const fieldDirectives = this.parseDirectives(
105 (field as FieldNode).directives || []
106 )
107 if (fieldDirectives.length > 0) {
108 hasDirectives = true
109 directivesMap[fieldName] = fieldDirectives
110 }
111 })
112 return hasDirectives ? directivesMap : undefined
113 }
114
115 private extractEntities(
116 node: SelectionSetNode,
117 parentName = "",
118 mainService = ""
119 ): Entity[] {
120 const entities: Entity[] = []
121
122 node.selections.forEach((selection) => {
123 if (selection.kind === "Field") {
124 const fieldNode = selection as FieldNode
125
126 if (!fieldNode.selectionSet) {
127 return
128 }
129
130 const propName = fieldNode.name.value
131 const entityName = parentName ? `${parentName}.${propName}` : propName
132
133 const nestedEntity: Entity = {
134 property: entityName.replace(`${mainService}.`, ""),
135 fields: fieldNode.selectionSet.selections.map(
136 (field) => (field as FieldNode).name.value
137 ),
138 args: this.parseArguments(fieldNode.arguments || []),
139 directives: this.createDirectivesMap(fieldNode.selectionSet),
140 }
141
142 entities.push(nestedEntity)
143 entities.push(
144 ...this.extractEntities(
145 fieldNode.selectionSet,
146 entityName,
147 mainService
148 )
149 )
150 }
151 })
152
153 return entities
154 }
155
156 public parseQuery(): RemoteJoinerQuery {
157 const queryDefinition = this.ast.definitions.find(
158 (definition) => definition.kind === "OperationDefinition"
159 ) as OperationDefinitionNode
160
161 if (!queryDefinition) {
162 throw new Error("No query found")
163 }
164
165 const rootFieldNode = queryDefinition.selectionSet
166 .selections[0] as FieldNode
167 const propName = rootFieldNode.name.value
168
169 const remoteJoinConfig: RemoteJoinerQuery = {
170 alias: propName,
171 fields: [],
172 expands: [],
173 }
174
175 if (rootFieldNode.arguments) {
176 remoteJoinConfig.args = this.parseArguments(rootFieldNode.arguments)
177 }
178
179 if (rootFieldNode.selectionSet) {
180 remoteJoinConfig.fields = rootFieldNode.selectionSet.selections.map(
181 (field) => (field as FieldNode).name.value
182 )
183 remoteJoinConfig.directives = this.createDirectivesMap(
184 rootFieldNode.selectionSet
185 )
186 remoteJoinConfig.expands = this.extractEntities(
187 rootFieldNode.selectionSet,
188 propName,
189 propName
190 )
191 }
192
193 return remoteJoinConfig
194 }
195 }