-
Notifications
You must be signed in to change notification settings - Fork 90
/
stitching.ts
442 lines (411 loc) · 13.9 KB
/
stitching.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
import { GraphQLError, GraphQLSchema, Kind, SelectionSetNode } from "graphql"
import { amountSDL, amount } from "schema/v1/fields/money"
import gql from "lib/gql"
import { toGlobalId } from "graphql-relay"
import { delegateToSchema } from "@graphql-tools/delegate"
import { ArtworkVersionType } from "schema/v2/artwork_version"
import { WrapQuery } from "graphql-tools"
const orderTotals = [
"itemsTotal",
"sellerTotal",
"commissionFee",
"totalListPrice",
"buyerTotal",
"taxTotal",
"shippingTotal",
"transactionFee",
]
const orderTotalsSDL = orderTotals.map(amountSDL)
const lineItemTotals = ["shippingTotal", "listPrice", "commissionFee"]
const lineItemTotalsSDL = lineItemTotals.map(amountSDL)
const offerAmountFields = ["amount", "taxTotal", "shippingTotal", "buyerTotal"]
const offerAmountFieldsSDL = offerAmountFields.map(amountSDL)
export const exchangeStitchingEnvironment = ({
localSchema,
exchangeSchema,
}: {
localSchema: GraphQLSchema
exchangeSchema: GraphQLSchema & { transforms: any }
}) => {
type DetailsFactoryInput = { from: string; to: string }
/**
* This returns a resolver which can take an exchange OrderParty union
* and convert it into a metaphysics `OrderParty`.
*
* You pass in the field to get the details from, and and the new fieldName
*/
const partyUnionToDetailsFactory = ({ from, to }: DetailsFactoryInput) => {
// We abuse the query alias feature to make sure that all
// the data we need to generate the full object from
// is included.
//
// It's possible that this working around a bug in how the fragment is put
// together by graphql-tools.
const aliasedPartyFragment = (field, alias) => {
return gql`
... on CommerceOrder {
${alias}: ${field} {
__typename
... on CommerceUser {
__typename
id
}
... on CommercePartner {
__typename
id
}
}
}`
}
return {
// Bit of a magic in next line, when adding fragment, it seems
// all second level fields (e.g. b in this query { a { b } }) are
// ignored, so __typename and id couldn't be added, so the hack
// was to alias the fragment field and that gets the current fields
fragment: aliasedPartyFragment(from, to),
resolve: (parent, _args, context, info) => {
const typename = parent[to].__typename
const id = parent[to].id
// Make a call to the user or partner resolver on query to
// grab our Metaphysics representations
return (
info.mergeInfo
.delegateToSchema({
schema: localSchema,
operation: "query",
fieldName: typename === "CommerceUser" ? "user" : "partner",
args: {
id,
},
context,
info,
transforms: exchangeSchema.transforms,
})
// Re-jigger the type systems back into place, as right now
// it is considered a CommerceUser and clients will reject it.
.then((response) => {
response.__typename =
typename === "CommerceUser" ? "User" : "Partner"
return response
})
)
},
}
}
const buyerDetailsResolver = partyUnionToDetailsFactory({
from: "buyer",
to: "buyerDetails",
})
const sellerDetailsResolver = partyUnionToDetailsFactory({
from: "seller",
to: "sellerDetails",
})
const fromDetailsResolver = partyUnionToDetailsFactory({
from: "from",
to: "fromDetails",
})
const creditCardResolver = {
fragment: `fragment CommerceOrderCreditCard on CommerceOrder { creditCardId }`,
resolve: (parent, _args, context, info) => {
const id = parent.creditCardId
if (!id) {
return null
} else {
return info.mergeInfo.delegateToSchema({
schema: localSchema,
operation: "query",
fieldName: "creditCard",
args: {
id,
},
context,
info,
transforms: exchangeSchema.transforms,
})
}
},
}
// Map the totals array to a set of resolvers that call the amount function
// the type param is only used for the fragment name
const totalsResolvers = (type, totalSDLS) =>
reduceToResolvers(
totalSDLS.map((name) => ({
[name]: {
fragment: `fragment ${type}_${name} on ${type} { ${name}Cents currencyCode }`,
resolve: (parent, args, _context, _info) => {
return amount((_) => parent[name + "Cents"]).resolve(parent, args)
},
},
}))
)
// Used to convert an array of `key: resolvers` to a single obj
const reduceToResolvers = (arr) => arr.reduce((a, b) => ({ ...a, ...b }))
return {
// The SDL used to declare how to stitch an object
extensionSchema: gql`
extend type CommerceLineItem {
artwork: Artwork
artworkVersion: ArtworkVersion
artworkOrEditionSet: ArtworkOrEditionSetType
${lineItemTotalsSDL.join("\n")}
}
extend type CommerceBuyOrder {
buyerDetails: OrderParty
sellerDetails: OrderParty
creditCard: CreditCard
${orderTotalsSDL.join("\n")}
}
extend type CommerceOfferOrder {
buyerDetails: OrderParty
sellerDetails: OrderParty
creditCard: CreditCard
${orderTotalsSDL.join("\n")}
${amountSDL("offerTotal")}
}
extend interface CommerceOrder {
buyerDetails: OrderParty
sellerDetails: OrderParty
creditCard: CreditCard
${orderTotalsSDL.join("\n")}
}
extend type CommerceOffer {
fromDetails: OrderParty
${offerAmountFieldsSDL.join("\n")}
}
extend type Me {
orders(first: Int, last: Int, after: String, before: String, mode: CommerceOrderModeEnum, sellerId: String, sort: CommerceOrderConnectionSortEnum, states: [CommerceOrderStateEnum!]): CommerceOrderConnectionWithTotalCount
}
`,
// Resolvers for the above
resolvers: {
CommerceBuyOrder: {
// The money helper resolvers
...totalsResolvers("CommerceBuyOrder", orderTotals),
buyerDetails: buyerDetailsResolver,
sellerDetails: sellerDetailsResolver,
creditCard: creditCardResolver,
},
CommerceOfferOrder: {
...totalsResolvers("CommerceOfferOrder", orderTotals),
buyerDetails: buyerDetailsResolver,
sellerDetails: sellerDetailsResolver,
creditCard: creditCardResolver,
},
CommerceLineItem: {
artwork: {
fragment: `fragment CommerceLineItemArtwork on CommerceLineItem { artworkId }`,
resolve: (parent, _args, context, info) => {
const id = parent.artworkId
return info.mergeInfo.delegateToSchema({
schema: localSchema,
operation: "query",
fieldName: "artwork",
args: {
id,
},
context,
info,
})
},
},
artworkVersion: {
fragment: `fragment CommerceLineItemArtwork on CommerceLineItem { artworkVersionId }`,
resolve: (parent, _args, context, info) => {
const id = parent.artworkVersionId
const globalID = toGlobalId("ArtworkVersion", id)
return delegateToSchema({
schema: localSchema,
operation: "query",
fieldName: "node",
args: {
id: globalID,
},
context,
info,
transforms: exchangeSchema.transforms,
returnType: ArtworkVersionType,
})
},
},
artworkOrEditionSet: {
fragment: gql`
... on CommerceLineItem {
artworkId
editionSetId
}
`,
resolve: async (parent, _args, context, info) => {
const artworkId = parent.artworkId
const editionSetId = parent.editionSetId
if (editionSetId) {
return info.mergeInfo.delegateToSchema({
schema: localSchema,
operation: "query",
fieldName: "artwork",
args: {
id: artworkId,
},
context,
info,
transforms: [
// Wrap document takes a subtree as an AST node
new WrapQuery(
// path at which to apply wrapping and extracting
["artwork"],
(subtree: SelectionSetNode) => ({
// we create a wrapping AST Field
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: "editionSet",
},
arguments: [
{
kind: Kind.ARGUMENT,
name: {
kind: Kind.NAME,
value: "id",
},
value: {
kind: Kind.STRING,
value: editionSetId,
},
},
],
// Inside the field selection
selectionSet: subtree,
}),
// how to process the data result at path
(result) => {
return result.editionSet
}
),
],
})
}
return info.mergeInfo.delegateToSchema({
schema: localSchema,
operation: "query",
fieldName: "artwork",
args: {
id: artworkId,
},
context,
info,
})
},
},
...totalsResolvers("CommerceLineItem", lineItemTotals),
},
CommerceOrder: {
// The money helper resolvers
...totalsResolvers("CommerceOrder", orderTotals),
buyerDetails: buyerDetailsResolver,
sellerDetails: sellerDetailsResolver,
creditCard: creditCardResolver,
},
CommerceOffer: {
...totalsResolvers("CommerceOffer", offerAmountFields),
fromDetails: fromDetailsResolver,
},
Me: {
orders: {
fragment: gql`... on Me {
__typename
}`,
resolve: async (_source, args, context, info) => {
return await info.mergeInfo.delegateToSchema({
schema: exchangeSchema,
operation: "query",
fieldName: "commerceMyOrders",
args,
context,
info,
})
},
},
},
Mutation: {
// monkey-patch the existing exchange mutation
// to add operations dependent on impulse
commerceCreateInquiryOfferOrderWithArtwork: {
resolve: async (_source, args, context, info) => {
const {
conversationLoader,
conversationCreateConversationOrderLoader,
} = context
const {
input: { impulseConversationId },
} = args
try {
await conversationLoader(impulseConversationId)
} catch (e) {
throw new GraphQLError(
`[metaphysics @ exchange/v2/stitching] Conversation not found`
)
}
const offerResult = await info.mergeInfo.delegateToSchema({
schema: exchangeSchema,
operation: "mutation",
fieldName: "commerceCreateInquiryOfferOrderWithArtwork",
args,
context,
info,
// transforms: [
// new WrapQuery(
// [
// "createInquiryOfferOrderWithArtwork",
// "orderOrError",
// "order",
// ],
// (selectionSet: SelectionSetNode) => {
// // const newSelections = [
// // ...selectionSet.selections,
// return {
// kind: Kind.FIELD,
// name: {
// kind: Kind.NAME,
// value: "internalID",
// },
// selectionSet,
// }
// // ]
// // return { ...selectionSet, selections: newSelections }
// },
// (result) => result
// // result.createInquiryOfferOrderWithArtwork.orderOrError.order
// ),
// ],
})
const { orderOrError } = offerResult
if (orderOrError.error) {
// if we got an error from exchange, return it immediately
return offerResult
} else if (orderOrError.order) {
// attempt to associate the order with the conversation
const {
order: { internalID: orderId },
} = orderOrError
if (!orderId) {
throw new GraphQLError(
"[metaphysics @ exchange/v2/stitching] Order.orderID field must be selected"
)
}
try {
await conversationCreateConversationOrderLoader({
conversation_id: impulseConversationId,
exchange_order_id: orderId,
})
} catch (e) {
throw new GraphQLError(
"[metaphysics @ exchange/v2/stitching] Impulse: request to associate offer with conversation failed"
)
}
}
return offerResult
},
},
},
},
}
}