This repository has been archived by the owner on Sep 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathindex.js
335 lines (309 loc) · 8.63 KB
/
index.js
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
import { parse, print } from 'graphql';
import Neo4jSchemaTree from './neo4j-schema/Neo4jSchemaTree';
import graphQLMapper from './neo4j-schema/graphQLMapper';
import { checkRequestError } from './auth';
import { translateMutation, translateQuery } from './translate';
import Debug from 'debug';
import {
extractQueryResult,
isMutation,
typeIdentifiers,
getPayloadSelections
} from './utils';
import {
augmentedSchema,
makeAugmentedExecutableSchema,
mapDefinitions,
mergeDefinitionMaps
} from './augment/augment';
import {
augmentTypes,
transformNeo4jTypes,
isSchemaDocument
} from './augment/types/types';
import { buildDocument } from './augment/ast';
import { augmentDirectiveDefinitions } from './augment/directives';
import { isFederatedOperation, executeFederatedOperation } from './federation';
import { schemaAssert } from './schemaAssert';
const neo4jGraphQLVersion = require('../package.json').version;
const debug = Debug('neo4j-graphql-js');
export async function neo4jgraphql(
object,
params,
context,
resolveInfo,
debugFlag
) {
if (isFederatedOperation({ resolveInfo })) {
return await executeFederatedOperation({
object,
params,
context,
resolveInfo,
debugFlag
});
} else {
// throw error if context.req.error exists
if (checkRequestError(context)) {
throw new Error(checkRequestError(context));
}
if (!context.driver) {
throw new Error(
"No Neo4j JavaScript driver instance provided. Please ensure a Neo4j JavaScript driver instance is injected into the context object at the key 'driver'."
);
}
let query;
let cypherParams;
const cypherFunction = isMutation(resolveInfo)
? cypherMutation
: cypherQuery;
[query, cypherParams] = cypherFunction(
params,
context,
resolveInfo,
debugFlag
);
if (debugFlag) {
console.log(`
Deprecation Warning: Remove \`debug\` parameter and use an environment variable
instead: \`DEBUG=neo4j-graphql-js\`.
`);
console.log(query);
console.log(JSON.stringify(cypherParams, null, 2));
}
debug('%s', query);
debug('%s', JSON.stringify(cypherParams, null, 2));
context.driver._userAgent = `neo4j-graphql-js/${neo4jGraphQLVersion}`;
let session;
const buildSessionParams = ctx => {
let paramObj = {};
if (ctx.neo4jDatabase) {
paramObj['database'] = ctx.neo4jDatabase;
}
if (ctx.neo4jBookmarks) {
paramObj['bookmarks'] = ctx.neo4jBookmarks;
}
return paramObj;
};
if (context.neo4jDatabase || context.neo4jBookmarks) {
const sessionParams = buildSessionParams(context);
try {
// connect to the specified database and/or use bookmarks
// must be using 4.x version of driver
session = context.driver.session(sessionParams);
} catch (e) {
// throw error if bookmark is specified as failure is better than ignoring user provided bookmark
if (context.neo4jBookmarks) {
throw new Error(
`context.neo4jBookmarks specified, but unable to set bookmark in session object: ${e.message}`
);
} else {
// error - not using a 4.x version of driver!
// fall back to default database
session = context.driver.session();
}
}
} else {
// no database or bookmark specified
session = context.driver.session();
}
let result;
try {
if (isMutation(resolveInfo)) {
result = await session.writeTransaction(tx => {
return tx.run(query, cypherParams);
});
} else {
result = await session.readTransaction(tx => {
return tx.run(query, cypherParams);
});
}
} finally {
session.close();
}
return extractQueryResult(result, resolveInfo.returnType);
}
}
export function cypherQuery(
{ first = -1, offset = 0, _id, orderBy, ...otherParams },
context,
resolveInfo
) {
const { typeName, variableName } = typeIdentifiers(resolveInfo.returnType);
const schemaType = resolveInfo.schema.getType(typeName);
const selections = getPayloadSelections(resolveInfo);
return translateQuery({
resolveInfo,
context,
schemaType,
selections,
variableName,
typeName,
first,
offset,
_id,
orderBy,
otherParams
});
}
export function cypherMutation(
{ first = -1, offset = 0, _id, orderBy, ...otherParams },
context,
resolveInfo
) {
const { typeName, variableName } = typeIdentifiers(resolveInfo.returnType);
const schemaType = resolveInfo.schema.getType(typeName);
const selections = getPayloadSelections(resolveInfo);
return translateMutation({
resolveInfo,
context,
schemaType,
selections,
variableName,
typeName,
first,
offset,
otherParams
});
}
export const augmentTypeDefs = (typeDefs, config = {}) => {
config.query = false;
config.mutation = false;
if (config.isFederated === undefined) config.isFederated = false;
const isParsedTypeDefs = isSchemaDocument({ definition: typeDefs });
let definitions = [];
if (isParsedTypeDefs) {
// Print if we recieved parsed type definitions in a GraphQL Document
definitions = typeDefs.definitions;
} else {
// Otherwise parse the SDL and get its definitions
definitions = parse(typeDefs).definitions;
}
let generatedTypeMap = {};
let [
typeDefinitionMap,
typeExtensionDefinitionMap,
directiveDefinitionMap,
operationTypeMap,
schemaTypeDefinition
] = mapDefinitions({
definitions,
config
});
[
typeExtensionDefinitionMap,
generatedTypeMap,
operationTypeMap
] = augmentTypes({
typeDefinitionMap,
typeExtensionDefinitionMap,
generatedTypeMap,
operationTypeMap,
config
});
[typeDefinitionMap, directiveDefinitionMap] = augmentDirectiveDefinitions({
typeDefinitionMap: generatedTypeMap,
directiveDefinitionMap,
config
});
const mergedDefinitions = mergeDefinitionMaps({
generatedTypeMap,
typeExtensionDefinitionMap,
operationTypeMap,
directiveDefinitionMap,
schemaTypeDefinition
});
const transformedDefinitions = transformNeo4jTypes({
definitions: mergedDefinitions,
config
});
const documentAST = buildDocument({
definitions: transformedDefinitions
});
if (config.isFederated === true) {
return documentAST;
}
return print(documentAST);
};
export const augmentSchema = (schema, config) => {
return augmentedSchema(schema, config);
};
export const makeAugmentedSchema = ({
schema,
typeDefs,
resolvers = {},
logger,
allowUndefinedInResolve = false,
resolverValidationOptions = {},
directiveResolvers = null,
schemaDirectives = {},
parseOptions = {},
inheritResolversFromInterfaces = false,
config
}) => {
if (schema) {
return augmentedSchema(schema, config);
}
if (!typeDefs) throw new Error('Must provide typeDefs');
return makeAugmentedExecutableSchema({
typeDefs,
resolvers,
logger,
allowUndefinedInResolve,
resolverValidationOptions,
directiveResolvers,
schemaDirectives,
parseOptions,
inheritResolversFromInterfaces,
config
});
};
/**
* Infer a GraphQL schema by inspecting the contents of a Neo4j instance.
* @param {} driver
* @returns a GraphQL schema.
*/
export const inferSchema = (driver, config = {}) => {
const tree = new Neo4jSchemaTree(driver, config);
return tree.initialize().then(graphQLMapper);
};
export const cypher = (statement, ...substitutions) => {
// Get the array of string literals
const literals = statement.raw;
// Add each substitution inbetween all
const composed = substitutions.reduce((composed, substitution, index) => {
// Add the string literal
composed.push(literals[index]);
// Add the substution proceeding it
composed.push(substitution);
return composed;
}, []);
// Add the last literal
composed.push(literals[literals.length - 1]);
return `statement: """${composed.join('')}"""`;
};
export const assertSchema = ({
driver,
schema,
dropExisting = true,
debug = false
}) => {
const statement = schemaAssert({ schema, dropExisting });
const executeQuery = driver => {
const session = driver.session();
return session
.writeTransaction(tx => tx.run(statement))
.then(result => {
if (debug === true) {
const recordsJSON = result.records.map(record => record.toObject());
recordsJSON.sort((lhs, rhs) => lhs.label < rhs.label);
console.table(recordsJSON);
}
return result;
})
.finally(() => session.close());
};
return executeQuery(driver).catch(error => {
console.error(error);
});
};