-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostGraphileManyCreatePlugin.ts
337 lines (313 loc) · 10.6 KB
/
PostGraphileManyCreatePlugin.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
import * as T from "./pluginTypes";
import debugFactory from "debug";
const debug = debugFactory("graphile-build-pg");
import { createTypeWithoutNestedInputTypes } from "./utils";
const PostGraphileManyCreatePlugin: T.Plugin = (builder: T.SchemaBuilder) => {
/**
* Add a hook to create the new root level create mutation
*/
builder.hook(
// @ts-ignore
"GraphQLObjectType:fields",
GQLObjectFieldsHookHandlerFcn,
["PgMutationManyCreate"], // Hook provides
[], // Hook before
["PgMutationCreate"] // Hook after
);
/**
* Handles adding the new "many create" root level fields
*/
function GQLObjectFieldsHookHandlerFcn(
fields: any,
build: T.Build,
context: T.Context
) {
const {
extend,
newWithHooks,
parseResolveInfo,
pgIntrospectionResultsByKind,
pgGetGqlTypeByTypeIdAndModifier,
pgGetGqlInputTypeByTypeIdAndModifier,
pgSql: sql,
gql2pg,
graphql: {
GraphQLObjectType,
GraphQLInputObjectType,
GraphQLNonNull,
GraphQLString,
GraphQLList,
},
pgColumnFilter,
inflection,
pgQueryFromResolveData: queryFromResolveData,
pgOmit: omit,
pgViaTemporaryTable: viaTemporaryTable,
describePgEntity,
sqlCommentByAddingTags,
pgField,
} = build;
const {
scope: { isRootMutation },
fieldWithHooks,
} = context;
if (!isRootMutation) return fields;
let newFields: object = {},
i: number;
const noOfTables = pgIntrospectionResultsByKind.class.length;
for (i = 0; i < noOfTables; i++) {
handleAdditionsFromTableInfo(pgIntrospectionResultsByKind.class[i]);
}
function handleAdditionsFromTableInfo(table: T.PgClass) {
if (
!table.namespace ||
!table.isSelectable ||
!table.isInsertable ||
omit(table, "create") ||
!table.tags.mncud
)
return;
const tableType: T.GraphQLType = pgGetGqlTypeByTypeIdAndModifier(
table.type.id,
null
);
if (!tableType) {
debug(
`There was no table type for table '${table.namespace.name}.${table.name}', so we're not generating a create mutation for it.`
);
return;
}
const TableInput = pgGetGqlInputTypeByTypeIdAndModifier(
table.type.id,
null
);
if (!TableInput) {
debug(
`There was no input type for table '${table.namespace.name}.${table.name}', so we're going to omit it from the create mutation.`
);
return;
}
const tableTypeName = inflection.tableType(table);
const newInputType = createTypeWithoutNestedInputTypes(TableInput);
// Setup args for the input type
const newInputHookType = GraphQLInputObjectType;
const newInputHookSpec = {
name: inflection.camelCase(inflection.createInputType(table)),
description: `All input for the create mn\`${tableTypeName}\` mutation.`,
fields: () => ({
clientMutationId: {
description:
"An arbitrary string value with no semantic meaning. Will be included in the payload verbatim. May be used to track mutations by the client.",
type: GraphQLString,
},
[inflection.pluralize(inflection.camelCase(tableTypeName))]: {
description: `The one or many \`${tableTypeName}\` to be created by this mutation.`,
type: new GraphQLList(new GraphQLNonNull(newInputType)),
},
}),
};
const newInputHookScope = {
__origin: `Adding many table create input type for ${describePgEntity(
table
)}.
You can rename the table's GraphQL type via a 'Smart Comment':
\n\n ${sqlCommentByAddingTags(table, {
name: "newNameHere",
})}`,
isPgCreateInputType: true,
pgInflection: table,
pgIntrospection: table,
};
const InputType = newWithHooks(
newInputHookType,
newInputHookSpec,
newInputHookScope
);
// Setup args for payload type
const newPayloadHookType = GraphQLObjectType;
const newPayloadHookSpec = {
name: inflection.pluralize(inflection.createPayloadType(table)),
description: `The output of our many create \`${tableTypeName}\` mutation.`,
fields: ({ fieldWithHooks }) => {
const tableName = inflection.tableFieldName(table);
return {
clientMutationId: {
description:
"The exact same `clientMutationId` that was provided in the mutation input, unchanged and unused. May be used by a client to track mutations.",
type: GraphQLString,
},
[tableName]: pgField(
build,
fieldWithHooks,
tableName,
{
description: `The \`${tableTypeName}\` that was created by this mutation.`,
type: new GraphQLList(new GraphQLNonNull(tableType)),
},
{
isPgCreatePayloadResultField: true,
pgFieldIntrospection: table,
}
),
};
},
};
const newPayloadHookScope = {
__origin: `Adding many table many create payload type for ${describePgEntity(
table
)}.
You can rename the table's GraphQL type via a 'Smart Comment':
\n\n ${sqlCommentByAddingTags(table, {
name: "newNameHere",
})}\n\nor disable the built-in create mutation via:\n\n
${sqlCommentByAddingTags(table, { omit: "create" })}`,
isMutationPayload: true,
isPgCreatePayloadType: true,
pgIntrospection: table,
};
const PayloadType = newWithHooks(
newPayloadHookType,
newPayloadHookSpec,
newPayloadHookScope
);
const fieldName = inflection.pluralize(
inflection.camelCase(inflection.createField(table))
);
function newFieldWithHooks(): T.FieldWithHooksFunction {
return fieldWithHooks(
fieldName,
(context) => {
context.table = table;
context.relevantAttributes = table.attributes.filter(
(attr) =>
pgColumnFilter(attr, build, context) && !omit(attr, "create")
);
return {
description: `Creates one or many \`${tableTypeName}\`.`,
type: PayloadType,
args: {
input: {
type: new GraphQLNonNull(InputType),
},
},
resolve: resolver.bind(context),
};
},
{
pgFieldIntrospection: table,
isPgCreateMutationField: true,
isMultipleMutation: true,
}
);
}
async function resolver(_data, args, resolveContext, resolveInfo) {
const { input } = args;
const {
table,
getDataFromParsedResolveInfoFragment,
relevantAttributes,
}: {
table: T.PgClass;
getDataFromParsedResolveInfoFragment: any;
relevantAttributes: any;
// @ts-ignore
} = this;
const { pgClient } = resolveContext;
const parsedResolveInfoFragment = parseResolveInfo(resolveInfo);
// @ts-ignore
parsedResolveInfoFragment.args = args; // Allow overriding via makeWrapResolversPlugin
const resolveData = getDataFromParsedResolveInfoFragment(
parsedResolveInfoFragment,
PayloadType
);
const insertedRowAlias = sql.identifier(Symbol());
const query = queryFromResolveData(
insertedRowAlias,
insertedRowAlias,
resolveData,
{},
null,
resolveContext,
resolveInfo.rootValue
);
const sqlColumns: T.SQL[] = [];
const inputData: Object[] =
input[
inflection.pluralize(
inflection.camelCase(inflection.tableFieldName(table))
)
];
if (!inputData || inputData.length === 0) return null;
const sqlValues: T.SQL[][] = Array(inputData.length).fill([]);
inputData.forEach((dataObj, i) => {
relevantAttributes.forEach((attr: T.PgAttribute) => {
const fieldName = inflection.column(attr);
const dataValue = dataObj[fieldName];
// On the first run, store the attribute values
if (i === 0) {
sqlColumns.push(sql.identifier(attr.name));
}
// If the key exists, store the data else store DEFAULT.
if (Object.prototype.hasOwnProperty.call(dataObj, fieldName)) {
sqlValues[i] = [
...sqlValues[i],
gql2pg(dataValue, attr.type, attr.typeModifier),
];
} else {
sqlValues[i] = [...sqlValues[i], sql.raw("default")];
}
});
});
const mutationQuery = sql.query`
INSERT INTO ${sql.identifier(table.namespace.name, table.name)}
${
sqlColumns.length
? sql.fragment`(${sql.join(sqlColumns, ", ")})
VALUES (${sql.join(
sqlValues.map(
(dataGroup) => sql.fragment`${sql.join(dataGroup, ", ")}`
),
"),("
)})`
: sql.fragment`default values`
} returning *`;
let rows;
try {
await pgClient.query("SAVEPOINT graphql_mutation");
rows = await viaTemporaryTable(
pgClient,
sql.identifier(table.namespace.name, table.name),
mutationQuery,
insertedRowAlias,
query
);
await pgClient.query("RELEASE SAVEPOINT graphql_mutation");
} catch (e) {
await pgClient.query("ROLLBACK TO SAVEPOINT graphql_mutation");
throw e;
}
return {
clientMutationId: input.clientMutationId,
data: rows,
};
}
newFields = extend(
newFields,
{
[fieldName]: newFieldWithHooks,
},
`Adding create mutation for ${describePgEntity(table)}. You can omit
this default mutation with a 'Smart Comment':\n\n
${sqlCommentByAddingTags(table, {
omit: "create",
})}`
);
}
return extend(
fields,
newFields,
`Adding the many 'create' mutation to the root mutation`
);
}
};
export default PostGraphileManyCreatePlugin;