/
connection.ts
339 lines (289 loc) · 8.91 KB
/
connection.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
import {
GraphQLInt,
GraphQLObjectType,
GraphQLNonNull,
GraphQLList,
GraphQLBoolean,
} from 'graphql';
import { first, last } from 'lodash';
import { GraphQLCursor } from './dataTypes';
import { resolveByFind } from './resolver';
import { ProtocolGraphQL } from './ProtocolGraphQL';
import { ProtocolGraphQLConfiguration } from './ProtocolGraphQLConfiguration';
import { generateSortInput } from './sort';
import { generateFilterInput } from './filter';
import { ConnectionNode } from './types';
// import { Entity } from '../engine/entity/Entity';
export const generateConnectionArgs = (entity, graphRegistry) => {
const sortInput = generateSortInput(entity);
const filterInput = generateFilterInput(entity, graphRegistry);
return {
first: {
type: GraphQLInt,
},
after: {
type: GraphQLCursor,
},
last: {
type: GraphQLInt,
},
before: {
type: GraphQLCursor,
},
offset: {
type: GraphQLInt,
},
orderBy: {
...sortInput,
},
filter: {
...filterInput,
},
};
};
export const validateConnectionArgs = (
_source,
args,
// _context,
// _info,
): void => {
const protocolConfiguration = ProtocolGraphQL.getProtocolConfiguration() as ProtocolGraphQLConfiguration;
// const maxPageSize = protocolConfiguration.getMaxPageSize(
// source,
// args,
// context,
// info,
// );
const maxPageSize = protocolConfiguration.getMaxPageSize();
if (args.first >= 0 && args.last >= 0) {
throw new Error('`first` and `last` settings are mutual exclusive');
}
if (args.first && (args.first < 0 || args.first > maxPageSize)) {
throw new Error(
`\`first\` needs to be within the range of 0 and ${maxPageSize}`,
);
}
if (args.last && (args.last < 0 || args.last > maxPageSize)) {
throw new Error(
`\`last\` needs to be within the range of 0 and ${maxPageSize}`,
);
}
if (args.offset && args.offset < 0) {
throw new Error('`offset` needs to be an integer starting from 0');
}
};
export const forceSortByUnique = (orderBy, entity): void => {
const attributes = entity.getAttributes();
let foundUnique = false;
orderBy.map(({ attribute }) => {
const { unique } = attributes[attribute];
if (unique) {
foundUnique = true;
}
});
if (!foundUnique) {
if (entity.getPrimaryAttribute()) {
const primaryAttribute = entity.getPrimaryAttribute();
orderBy.push({
attribute: primaryAttribute.name,
direction: 'ASC',
});
}
}
};
const pageInfoType = new GraphQLObjectType({
name: 'PageInfo',
description: 'Information about pagination in a connection.',
fields: () => ({
hasNextPage: {
type: new GraphQLNonNull(GraphQLBoolean),
description: 'When paginating forwards, are there more items?',
},
hasPreviousPage: {
type: new GraphQLNonNull(GraphQLBoolean),
description: 'When paginating backwards, are there more items?',
},
startCursor: {
type: GraphQLCursor,
description: 'When paginating backwards, the cursor to continue.',
},
endCursor: {
type: GraphQLCursor,
description: 'When paginating forwards, the cursor to continue.',
},
}),
});
export const generateConnectionType = config => {
// const protocolConfiguration = ProtocolGraphQL.getProtocolConfiguration();
const protocolConfiguration = ProtocolGraphQL.getProtocolConfiguration() as ProtocolGraphQLConfiguration;
const { nodeType, entity } = config;
const typeNamePluralListName = entity.graphql.typeNamePluralPascalCase;
let cursor;
if (entity.getPrimaryAttribute()) {
cursor = {
type: new GraphQLNonNull(GraphQLCursor),
description: 'A cursor for use in pagination',
};
}
const edgeType = new GraphQLObjectType({
name: protocolConfiguration.generateConnectionEdgeTypeName(entity),
description: 'An edge in a connection.',
fields: () => ({
node: {
type: nodeType,
description: 'The item at the end of the edge',
},
...(cursor && { cursor }),
}),
});
const connectionType = new GraphQLObjectType({
name: protocolConfiguration.generateConnectionTypeName(entity),
description: 'A connection to a list of items.',
fields: () => ({
pageInfo: {
type: new GraphQLNonNull(pageInfoType),
description: 'Information to aid in pagination.',
},
edges: {
type: new GraphQLList(edgeType),
description: 'A list of edges.',
},
totalCount: {
type: GraphQLInt,
description: `The count of all **\`${typeNamePluralListName}\`** you could get from the connection.`,
},
resultCount: {
type: GraphQLInt,
description: `The count of **\`${typeNamePluralListName}\`** in this result set.`,
resolve: ({ edges }) => edges.length,
},
}),
});
return {
edgeType,
connectionType,
};
};
export const buildCursor = (entityName, primaryAttributeName, args, data) => {
const cursor = [];
let primaryAttributeAdded = false;
if (args && args.orderBy) {
args.orderBy.map(({ attribute }) => {
cursor.push([attribute, data[attribute]]);
if (attribute === primaryAttributeName) {
primaryAttributeAdded = true;
}
});
}
if (!primaryAttributeAdded) {
cursor.push([primaryAttributeName, data[primaryAttributeName]]);
}
return {
[entityName]: cursor,
};
};
export const connectionFromData = (
{ transformedData, originalData },
entity,
_source,
args,
context,
_info,
parentConnection,
pageInfoFromData,
) => {
const entityName = entity.name;
let nodeToEdge: (node: any, idx?: number) => ConnectionNode;
if (entity.getPrimaryAttribute()) {
const primaryAttributeName = entity.getPrimaryAttribute().name;
nodeToEdge = (node, idx) => ({
cursor: buildCursor(
entityName,
primaryAttributeName,
args,
originalData[idx],
),
node,
});
} else {
nodeToEdge = node => ({
node,
});
}
const edges: ConnectionNode[] = transformedData.map(nodeToEdge);
const firstNode = first(edges);
const lastNode = last(edges);
return {
edges,
totalCount: async () => {
const storageType = entity.storageType;
return storageType.count(entity, args, context, parentConnection);
},
pageInfo: {
startCursor: firstNode ? firstNode.cursor : null,
endCursor: lastNode ? lastNode.cursor : null,
hasPreviousPage: pageInfoFromData.hasPreviousPage,
hasNextPage: pageInfoFromData.hasNextPage,
},
};
};
export const registerConnection = (graphRegistry, entity) => {
const typeName = entity.graphql.typeName;
const type = graphRegistry.types[typeName].type;
const { connectionType } = generateConnectionType({
nodeType: type,
entity,
});
const connectionArgs = generateConnectionArgs(entity, graphRegistry);
graphRegistry.types[typeName].connection = connectionType;
graphRegistry.types[typeName].connectionArgs = connectionArgs;
};
export const generateReverseConnections = (
configuration,
graphRegistry,
entity,
) => {
const schema = configuration.getSchema();
const schemaEntities = schema.getEntities();
const protocolConfiguration = ProtocolGraphQL.getProtocolConfiguration() as ProtocolGraphQLConfiguration;
const fields = {};
const typeNamePascalCase = entity.graphql.typeNamePascalCase;
entity.referencedByEntities.map(
({ sourceEntityName, sourceAttributeName }) => {
const sourceEntity = schemaEntities[sourceEntityName];
if (!sourceEntity) {
throw new Error(
`Failed to create reverse connection for entity '${sourceEntityName}' as it was not found`,
);
}
const sourceEntityTypeName = protocolConfiguration.generateEntityTypeName(
sourceEntity,
);
const fieldName = protocolConfiguration.generateReverseConnectionFieldName(
sourceEntity,
sourceAttributeName,
);
const typeNamePluralListName =
sourceEntity.graphql.typeNamePluralPascalCase;
fields[fieldName] = {
type: graphRegistry.types[sourceEntityTypeName].connection,
description: `Fetch a list of **\`${typeNamePluralListName}\`** for a given **\`${typeNamePascalCase}\`**\n${sourceEntity.descriptionPermissionsFind ||
''}`,
args: graphRegistry.types[sourceEntityTypeName].connectionArgs,
resolve: resolveByFind(sourceEntity, ({ source, info }) => {
const parentEntityTypeName = protocolConfiguration.generateEntityTypeName(
info.parentType,
);
const parentEntity = graphRegistry.types[parentEntityTypeName].entity;
const parentAttribute = parentEntity.getPrimaryAttribute();
const parentConnection = {
id: source[parentAttribute.gqlFieldName],
attribute: sourceAttributeName,
};
return parentConnection;
}),
};
},
);
return fields;
};