-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathuse-query-public.tsx
More file actions
366 lines (335 loc) · 10.8 KB
/
Copy pathuse-query-public.tsx
File metadata and controls
366 lines (335 loc) · 10.8 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
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
import { type Entity, type Mapping, type MappingEntry, Type, store } from '@graphprotocol/hypergraph';
import { useQuery as useQueryTanstack } from '@tanstack/react-query';
import { useSelector } from '@xstate/store/react';
import * as Either from 'effect/Either';
import * as Schema from 'effect/Schema';
import { gql, request } from 'graphql-request';
import { useMemo } from 'react';
import { useHypergraphSpaceInternal } from '../HypergraphSpaceContext.js';
import { GEO_API_TESTNET_ENDPOINT } from './constants.js';
import type { QueryPublicParams } from './types.js';
const entitiesQueryDocumentLevel0 = gql`
query entities($spaceId: UUID!, $typeIds: [UUID!]!, $first: Int) {
entities(
filter: {
relations: {some: {typeId: {is: "8f151ba4-de20-4e3c-9cb4-99ddf96f48f1"}, toEntityId: {in: $typeIds}}}, spaceIds: {in: [$spaceId]}},
first: $first
) {
id
name
valuesList(filter: {spaceId: {is: $spaceId}}) {
propertyId
value
}
}
}
`;
const entitiesQueryDocumentLevel1 = gql`
query entities($spaceId: UUID!, $typeIds: [UUID!]!, $relationTypeIdsLevel1: [UUID!]!, $first: Int) {
entities(
first: $first
filter: {
relations: {some: {typeId: {is: "8f151ba4-de20-4e3c-9cb4-99ddf96f48f1"}, toEntityId: {in: $typeIds}}}, spaceIds: {in: [$spaceId]}}) {
id
name
valuesList(filter: {spaceId: {is: $spaceId}}) {
propertyId
value
}
relationsList(
filter: {spaceId: {is: $spaceId}, typeId:{ in: $relationTypeIdsLevel1}},
) {
toEntity {
id
name
valuesList(filter: {spaceId: {is: $spaceId}}) {
propertyId
value
}
}
typeId
}
}
}
`;
const entitiesQueryDocumentLevel2 = gql`
query entities($spaceId: UUID!, $typeIds: [UUID!]!, $relationTypeIdsLevel1: [UUID!]!, $relationTypeIdsLevel2: [UUID!]!, $first: Int) {
entities(
first: $first
filter: {
relations: {some: {typeId: {is: "8f151ba4-de20-4e3c-9cb4-99ddf96f48f1"}, toEntityId: {in: $typeIds}}}, spaceIds: {in: [$spaceId]}}) {
id
name
valuesList(filter: {spaceId: {is: $spaceId}}) {
propertyId
value
}
relationsList(
filter: {spaceId: {is: $spaceId}, typeId:{ in: $relationTypeIdsLevel1}},
) {
toEntity {
id
name
valuesList(filter: {spaceId: {is: $spaceId}}) {
propertyId
value
}
relationsList(
filter: {spaceId: {is: $spaceId}, typeId:{ in: $relationTypeIdsLevel2}},
# filter: {spaceId: {is: $spaceId}, toEntity: {relations: {some: {typeId: {is: "8f151ba4-de20-4e3c-9cb4-99ddf96f48f1"}, toEntityId: {in: $relationTypeIdsLevel2}}}}}
) {
toEntity {
id
name
valuesList(filter: {spaceId: {is: $spaceId}}) {
propertyId
value
}
}
typeId
}
}
typeId
}
}
}
`;
type EntityQueryResult = {
entities: {
id: string;
name: string;
valuesList: {
propertyId: string;
value: string;
}[];
relationsList: {
toEntity: {
id: string;
name: string;
valuesList: {
propertyId: string;
value: string;
}[];
relationsList: {
toEntity: {
id: string;
name: string;
valuesList: {
propertyId: string;
value: string;
}[];
};
typeId: string;
}[];
};
typeId: string;
}[];
}[];
};
// A recursive representation of the entity structure returned by the public GraphQL
// endpoint. `values` and `relations` are optional because the nested `to` selections
// get slimmer the deeper we traverse in the query. This type intentionally mirrors
// only the fields we actually consume inside `convertRelations`.
type RecursiveQueryEntity = {
id: string;
name: string;
valuesList?: {
propertyId: string;
value: string;
}[];
relationsList?: {
toEntity: RecursiveQueryEntity;
typeId: string;
}[];
};
const convertPropertyValue = (
property: { propertyId: string; value: string },
key: string,
type: Entity.AnyNoContext,
) => {
if (type.fields[key] === Type.Checkbox) {
return Boolean(property.value);
}
if (type.fields[key] === Type.Point) {
return property.value;
}
if (type.fields[key] === Type.Url) {
return property.value;
}
if (type.fields[key] === Type.Date) {
return property.value;
}
if (type.fields[key] === Type.Number) {
return Number(property.value);
}
return property.value;
};
const convertRelations = <S extends Entity.AnyNoContext>(
queryEntity: RecursiveQueryEntity,
type: S,
mappingEntry: MappingEntry,
mapping: Mapping,
) => {
const rawEntity: Record<string, string | boolean | number | unknown[] | URL | Date> = {};
for (const [key, relationId] of Object.entries(mappingEntry?.relations ?? {})) {
const properties = (queryEntity.relationsList ?? []).filter((a) => a.typeId === relationId);
if (properties.length === 0) {
rawEntity[key] = [] as unknown[];
continue;
}
const field = type.fields[key];
if (!field) {
// @ts-expect-error TODO: properly access the type.name
console.error(`Field ${key} not found in ${type.name}`);
continue;
}
// @ts-expect-error TODO: properly access the type.name
const annotations = field.ast.rest[0].type.to.annotations;
// TODO: fix this access using proper effect types
const relationTypeName =
annotations[
Object.getOwnPropertySymbols(annotations).find((sym) => sym.description === 'effect/annotation/Identifier')
];
const relationMappingEntry = mapping[relationTypeName];
if (!relationMappingEntry) {
console.error(`Relation mapping entry for ${relationTypeName} not found`);
continue;
}
const newRelationEntities = properties.map((propertyEntry) => {
// @ts-expect-error TODO: properly access the type.name
const type = field.value;
let rawEntity: Record<string, string | boolean | number | unknown[] | URL | Date> = {
id: propertyEntry.toEntity.id,
name: propertyEntry.toEntity.name,
// TODO: should be determined by the actual value
__deleted: false,
// TODO: should be determined by the actual value
__version: '',
};
// take the mappingEntry and assign the attributes to the rawEntity
for (const [key, value] of Object.entries(relationMappingEntry?.properties ?? {})) {
const property = propertyEntry.toEntity.valuesList?.find((a) => a.propertyId === value);
if (property) {
rawEntity[key] = convertPropertyValue(property, key, type);
}
}
rawEntity = {
...rawEntity,
...convertRelations(propertyEntry.toEntity, type, relationMappingEntry, mapping),
};
return rawEntity;
});
if (rawEntity[key]) {
rawEntity[key] = [
// @ts-expect-error TODO: properly access the type.name
...rawEntity[key],
...newRelationEntities,
];
} else {
rawEntity[key] = newRelationEntities;
}
}
return rawEntity;
};
export const parseResult = <S extends Entity.AnyNoContext>(
queryData: EntityQueryResult,
type: S,
mappingEntry: MappingEntry,
mapping: Mapping,
) => {
const decode = Schema.decodeUnknownEither(type);
const data: Entity.Entity<S>[] = [];
const invalidEntities: Record<string, unknown>[] = [];
for (const queryEntity of queryData.entities) {
let rawEntity: Record<string, string | boolean | number | unknown[] | URL | Date> = {
id: queryEntity.id,
};
// take the mappingEntry and assign the attributes to the rawEntity
for (const [key, value] of Object.entries(mappingEntry?.properties ?? {})) {
const property = queryEntity.valuesList.find((a) => a.propertyId === value);
if (property) {
rawEntity[key] = convertPropertyValue(property, key, type);
}
}
rawEntity = {
...rawEntity,
...convertRelations(queryEntity, type, mappingEntry, mapping),
};
const decodeResult = decode({
...rawEntity,
__deleted: false,
// __version: queryEntity.currentVersion.versionId,
__version: '',
});
if (Either.isRight(decodeResult)) {
data.push({ ...decodeResult.right, __schema: type });
} else {
invalidEntities.push(rawEntity);
}
}
return { data, invalidEntities };
};
export const useQueryPublic = <S extends Entity.AnyNoContext>(type: S, params?: QueryPublicParams<S>) => {
const { enabled = true, include, first = 100 } = params ?? {};
const { space } = useHypergraphSpaceInternal();
const mapping = useSelector(store, (state) => state.context.mapping);
// @ts-expect-error TODO should use the actual type instead of the name in the mapping
const typeName = type.name;
const mappingEntry = mapping?.[typeName];
if (enabled && !mappingEntry) {
throw new Error(`Mapping entry for ${typeName} not found`);
}
// constructing the relation type ids for the query
const relationTypeIdsLevel1: string[] = [];
const relationTypeIdsLevel2: string[] = [];
for (const key in mappingEntry?.relations ?? {}) {
if (include?.[key] && mappingEntry?.relations?.[key]) {
relationTypeIdsLevel1.push(mappingEntry?.relations?.[key]);
const field = type.fields[key];
// @ts-expect-error TODO find a better way to access the relation type name
const typeName2 = field.value.name;
const mappingEntry2 = mapping[typeName2];
for (const key2 in mappingEntry2?.relations ?? {}) {
if (include?.[key][key2] && mappingEntry2?.relations?.[key2]) {
relationTypeIdsLevel2.push(mappingEntry2?.relations?.[key2]);
}
}
}
}
const result = useQueryTanstack({
queryKey: [
'hypergraph-public-entities',
typeName,
space,
mappingEntry?.typeIds,
relationTypeIdsLevel1,
relationTypeIdsLevel2,
// TODO should `first` be in here?
],
queryFn: async () => {
let queryDocument = entitiesQueryDocumentLevel0;
if (relationTypeIdsLevel1.length > 0) {
queryDocument = entitiesQueryDocumentLevel1;
}
if (relationTypeIdsLevel2.length > 0) {
queryDocument = entitiesQueryDocumentLevel2;
}
const result = await request<EntityQueryResult>(GEO_API_TESTNET_ENDPOINT, queryDocument, {
spaceId: space,
typeIds: mappingEntry?.typeIds || [],
relationTypeIdsLevel1,
relationTypeIdsLevel2,
first,
});
return result;
},
enabled,
});
const { data, invalidEntities } = useMemo(() => {
if (result.data && mappingEntry) {
return parseResult(result.data, type, mappingEntry, mapping);
}
return { data: [], invalidEntities: [] };
}, [result.data, type, mappingEntry, mapping]);
return { ...result, data, invalidEntities };
};