-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathorderResolver.ts
More file actions
218 lines (203 loc) · 6.2 KB
/
orderResolver.ts
File metadata and controls
218 lines (203 loc) · 6.2 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
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
import _ from "lodash";
import { inject, injectable } from "tsyringe";
import { Args, FieldResolver, Query, Resolver, Root } from "type-graphql";
import { getAddress } from "viem";
import { GetOrdersArgs } from "../../../graphql/schemas/args/orderArgs.js";
import {
GetOrdersResponse,
Order,
} from "../../../graphql/schemas/typeDefs/orderTypeDefs.js";
import { addPriceInUsdToOrder } from "../../../utils/addPriceInUSDToOrder.js";
import { getHypercertTokenId } from "../../../utils/tokenIds.js";
import { HypercertsService } from "../../database/entities/HypercertsEntityService.js";
import { MarketplaceOrdersService } from "../../database/entities/MarketplaceOrdersEntityService.js";
/**
* GraphQL resolver for marketplace orders.
* Handles queries for orders and resolves related fields.
*
* This resolver provides:
* - Query for fetching orders with optional filtering
* - Price calculation in USD for each order
* - Field resolution for:
* - hypercert: Associated hypercert details and metadata
*
* Error Handling:
* - Query operations throw errors to be handled by the GraphQL error handler
* - Field resolvers return null on errors to allow partial data resolution
* - All errors are logged for monitoring
*
* @injectable Marks the class as injectable for dependency injection with tsyringe
* @resolver Marks the class as a GraphQL resolver for the Order type
*/
@injectable()
@Resolver(() => Order)
class OrderResolver {
constructor(
@inject(MarketplaceOrdersService)
private readonly marketplaceOrdersService: MarketplaceOrdersService,
@inject(HypercertsService)
private readonly hypercertService: HypercertsService,
) {}
/**
* Queries marketplace orders based on provided arguments.
* Fetches associated hypercerts and calculates USD prices.
*
* @param args - Query arguments for filtering orders
* @returns A promise resolving to:
* - data: Array of orders with USD prices
* - count: Total number of matching records
* @throws Error if the operation fails
*
* @example
* ```graphql
* query {
* orders(
* where: {
* seller: { eq: "0x..." }
* status: { eq: "active" }
* }
* ) {
* data {
* id
* price
* priceInUsd
* seller
* status
* hypercert {
* id
* metadata {
* name
* description
* }
* }
* }
* count
* }
* }
* ```
*/
@Query(() => GetOrdersResponse)
async orders(@Args() args: GetOrdersArgs) {
try {
const ordersRes = await this.marketplaceOrdersService.getOrders(args);
if (!ordersRes || !ordersRes.data || !ordersRes.count) {
return {
data: [],
count: 0,
};
}
const { data, count } = ordersRes;
// Get unique hypercert IDs and convert to lowercase once
const allHypercertIds = _.uniq(
data.map((order) => order.hypercert_id as unknown as string),
);
// Fetch hypercerts in parallel with any other async operations
const { data: hypercertsData } =
await this.hypercertService.getHypercerts({
where: {
hypercert_id: { in: allHypercertIds },
},
});
// Create lookup map with lowercase keys
const hypercerts = new Map(
hypercertsData.map((h) => [
(h.hypercert_id as unknown as string)?.toLowerCase(),
h,
]),
);
// Process orders in parallel since addPriceInUsdToOrder is async
const ordersWithPrices = await Promise.all(
data.map(async (order) => {
const hypercert = hypercerts.get(
(order.hypercert_id as unknown as string)?.toLowerCase(),
);
if (!hypercert?.units) {
console.warn(
`[OrderResolver::orders] No hypercert units found for hypercert_id: ${order.hypercert_id}`,
);
return order;
}
return addPriceInUsdToOrder(
order,
hypercert.units as unknown as bigint,
);
}),
);
return {
data: ordersWithPrices,
count: count ?? ordersWithPrices.length,
};
} catch (e) {
throw new Error(
`[OrderResolver::orders] Error fetching orders: ${(e as Error).message}`,
);
}
}
/**
* Resolves the hypercert field for an order.
* This field resolver is called automatically when the hypercert field is requested in a query.
*
* @param order - The order for which to resolve the hypercert
* @returns A promise resolving to:
* - The hypercert with its metadata if found
* - null if:
* - Required fields are missing
* - An error occurs during retrieval
*
* @example
* ```graphql
* query {
* orders {
* data {
* id
* hypercert {
* id
* uri
* metadata {
* name
* description
* image
* }
* }
* }
* }
* }
* ```
*/
@FieldResolver({ nullable: true })
async hypercert(@Root() order: Order) {
try {
const tokenId = order.itemIds?.[0];
const collectionId = order.collection;
const chainId = order.chainId;
if (!tokenId || !collectionId || !chainId) {
console.warn(
`[OrderResolver::hypercert] Missing tokenId or collectionId`,
);
return null;
}
const hypercertId = getHypercertTokenId(BigInt(tokenId));
const formattedHypercertId = `${chainId}-${getAddress(collectionId)}-${hypercertId.toString()}`;
const [hypercert, metadata] = await Promise.all([
this.hypercertService.getHypercert({
where: {
hypercert_id: { eq: formattedHypercertId },
},
}),
this.hypercertService.getHypercertMetadata({
hypercert_id: formattedHypercertId,
}),
]);
return {
...hypercert,
metadata: metadata || null,
};
} catch (e) {
console.error(
`[OrderResolver::hypercert] Error resolving hypercert: ${(e as Error).message}`,
);
return null;
}
}
}
export { OrderResolver };