-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathprepare-publish.ts
More file actions
191 lines (176 loc) · 6.52 KB
/
Copy pathprepare-publish.ts
File metadata and controls
191 lines (176 loc) · 6.52 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
import {
Graph,
type GrcOp,
type Id,
type PropertiesParam,
type PropertyValueParam,
type RelationsParam,
} from '@graphprotocol/grc-20';
import { Config, Constants, type Entity, Utils } from '@graphprotocol/hypergraph';
import * as Option from 'effect/Option';
import type * as Schema from 'effect/Schema';
import * as SchemaAST from 'effect/SchemaAST';
import request, { gql } from 'graphql-request';
export type PreparePublishParams<S extends Schema.Schema.AnyNoContext> = {
entity: Entity.Entity<S>;
publicSpace: string | Id;
};
const entityToPublishQueryDocument = gql`
query entityToPublish($entityId: UUID!, $spaceId: UUID!) {
entity(id: $entityId) {
valuesList(filter: {spaceId: {is: $spaceId}}) {
propertyId
text
boolean
float
datetime
point
schedule
}
relationsList(filter: {spaceId: {is: $spaceId}}) {
id
}
}
}
`;
type EntityToPublishQueryResult = {
entity: {
valuesList: {
propertyId: string;
text: string;
boolean: boolean;
float: number;
datetime: string;
point: string;
schedule: string;
}[];
relationsList: {
id: string;
}[];
};
} | null;
export const preparePublish = async <S extends Schema.Schema.AnyNoContext>({
entity,
publicSpace,
}: PreparePublishParams<S>) => {
const data = await request<EntityToPublishQueryResult>(
`${Config.getApiOrigin()}/v2/graphql`,
entityToPublishQueryDocument,
{
entityId: entity.id,
spaceId: publicSpace,
},
);
const ops: GrcOp[] = [];
const values: PropertiesParam = [];
const relations: RelationsParam = {};
const type = entity.__schema;
const ast = type.ast as SchemaAST.TypeLiteral;
const typeIds = SchemaAST.getAnnotation<string[]>(Constants.TypeIdsSymbol)(ast).pipe(Option.getOrElse(() => []));
if (data?.entity === null) {
for (const prop of ast.propertySignatures) {
const propertyId = SchemaAST.getAnnotation<string>(Constants.PropertyIdSymbol)(prop.type);
const propertyType = SchemaAST.getAnnotation<string>(Constants.PropertyTypeSymbol)(prop.type);
if (!Option.isSome(propertyId) || !Option.isSome(propertyType)) continue;
if (Utils.isRelation(prop.type)) {
// @ts-expect-error any is ok here
relations[propertyId.value] = entity[prop.name].map((relationEntity) => {
const newRelation: Record<string, string> = { toEntity: relationEntity.id };
if (relationEntity._relation.id) {
newRelation.id = relationEntity._relation.id;
}
if (relationEntity._relation.position) {
newRelation.position = relationEntity._relation.position;
}
return newRelation;
});
} else {
if (entity[prop.name] === undefined) {
if (prop.isOptional) {
continue;
}
throw new Error(`Value for ${String(prop.name)} is undefined`);
}
let typedValue: PropertyValueParam;
if (propertyType.value === 'boolean') {
typedValue = { property: propertyId.value, type: 'bool', value: entity[prop.name] as boolean };
} else if (propertyType.value === 'date') {
const dateValue = entity[prop.name] as Date;
typedValue = { property: propertyId.value, type: 'date', value: dateValue.toISOString().split('T')[0] };
} else if (propertyType.value === 'point') {
const [lon, lat] = entity[prop.name] as [number, number];
typedValue = { property: propertyId.value, type: 'point', lon, lat };
} else if (propertyType.value === 'number') {
typedValue = { property: propertyId.value, type: 'float64', value: entity[prop.name] as number };
} else {
// string (text)
typedValue = { property: propertyId.value, type: 'text', value: entity[prop.name] as string };
}
values.push(typedValue);
}
}
const { ops: createOps } = Graph.createEntity({
id: entity.id,
types: typeIds,
values,
relations,
});
ops.push(...createOps);
return { ops };
}
if (!data) {
return { ops: [] };
}
for (const prop of ast.propertySignatures) {
const propertyId = SchemaAST.getAnnotation<string>(Constants.PropertyIdSymbol)(prop.type);
const propertyType = SchemaAST.getAnnotation<string>(Constants.PropertyTypeSymbol)(prop.type);
if (!Option.isSome(propertyId) || !Option.isSome(propertyType)) continue;
if (Utils.isRelation(prop.type)) {
// TODO: handle added or removed relations
// TODO: handle updated relations
} else {
if (entity[prop.name] === undefined) {
if (prop.isOptional) {
continue;
}
throw new Error(`Value for ${String(prop.name)} is undefined`);
}
const existingValueEntry = data.entity.valuesList.find((value) => value.propertyId === propertyId.value);
let hasChanged = false;
let typedValue: PropertyValueParam;
if (propertyType.value === 'boolean') {
const newValue = entity[prop.name] as boolean;
hasChanged = existingValueEntry?.boolean !== newValue;
typedValue = { property: propertyId.value, type: 'bool', value: newValue };
} else if (propertyType.value === 'date') {
const dateValue = entity[prop.name] as Date;
const newValue = dateValue.toISOString().split('T')[0];
hasChanged = existingValueEntry?.datetime !== newValue;
typedValue = { property: propertyId.value, type: 'date', value: newValue };
} else if (propertyType.value === 'point') {
const [lon, lat] = entity[prop.name] as [number, number];
const newValue = `${lon},${lat}`;
hasChanged = existingValueEntry?.point !== newValue;
typedValue = { property: propertyId.value, type: 'point', lon, lat };
} else if (propertyType.value === 'number') {
const newValue = entity[prop.name] as number;
hasChanged = existingValueEntry?.float !== newValue;
typedValue = { property: propertyId.value, type: 'float64', value: newValue };
} else {
// string (text)
const newValue = entity[prop.name] as string;
hasChanged = existingValueEntry?.text !== newValue;
typedValue = { property: propertyId.value, type: 'text', value: newValue };
}
if (hasChanged) {
values.push(typedValue);
}
}
}
// TODO: handle added or removed types
if (values.length > 0) {
const { ops: updateEntityOps } = Graph.updateEntity({ id: entity.id, values });
ops.push(...updateEntityOps);
}
return { ops };
};