Repository navigation
Expand file tree
/
Copy pathapolloClient.ts
More file actions
104 lines (97 loc) · 3.06 KB
/
Copy pathapolloClient.ts
File metadata and controls
104 lines (97 loc) · 3.06 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
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { ProductType, Format, Genre, ElectronicsCategory } from "./typeDefs";
type ArgsType = {
searchTerm: string;
productType: ProductType;
format: Format;
genres: Genre[];
category: ElectronicsCategory;
sortField: string;
sortOrder: string;
};
interface ProductRef {
__ref: string;
}
export const apolloClient = new ApolloClient({
uri: "http://it2810-14.idi.ntnu.no:3001/graphql",
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
products: {
// Cache based on arguments ('where' filter)
keyArgs: ["where"],
merge(_, incoming) {
return incoming;
},
},
searchProducts: {
keyArgs: ["searchTerm", "productType", "format", "genres", "category", "sortField", "sortOrder"],
merge(existing = [], incoming, { args }) {
// If any key argument has changed, replace existing data with incoming
if (args) {
const existingKeyArgs: ArgsType = {
searchTerm: args.searchTerm,
productType: args.productType,
format: args.format,
genres: args.genres,
category: args.category,
sortField: args.sortField,
sortOrder: args.sortOrder,
};
// Check if existing data matches incoming arguments
const isFreshDataNeeded = Object.keys(existingKeyArgs).some((key) => {
return existingKeyArgs[key as keyof ArgsType] !== args[key as keyof ArgsType];
});
// If arguments change, return incoming as fresh data
if (isFreshDataNeeded) {
return incoming;
}
}
// Create a map to ensure uniqueness
const productMap = new Map<string, ProductRef>(existing.map((item: ProductRef) => [item.__ref, item]));
incoming.forEach((item: ProductRef) => productMap.set(item.__ref, item));
return Array.from(productMap.values());
},
},
chats: {
merge(_, incoming) {
return incoming;
},
},
users: {
merge(_, incoming) {
return incoming;
},
},
},
},
CProduct: {
keyFields: ["id"], // Identify products uniquely by id
fields: {
favoritedBy: {
merge(_, incoming) {
return incoming;
},
},
},
},
User: {
fields: {
favoritedProducts: {
merge(_, incoming) {
// Replace the list with the incoming data.
return incoming;
},
},
productsForSale: {
merge(_, incoming) {
// Replace the list with the incoming data.
return incoming;
},
},
},
},
},
}),
});