/
PgMutationCreatePlugin.js
298 lines (290 loc) · 10.8 KB
/
PgMutationCreatePlugin.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
// @flow
import type { Plugin } from "graphile-build";
import debugFactory from "debug";
const debug = debugFactory("graphile-build-pg");
export default (function PgMutationCreatePlugin(
builder,
{ pgDisableDefaultMutations }
) {
if (pgDisableDefaultMutations) {
return;
}
builder.hook(
"GraphQLObjectType:fields",
(fields, build, context) => {
const {
extend,
newWithHooks,
parseResolveInfo,
pgIntrospectionResultsByKind,
pgGetGqlTypeByTypeIdAndModifier,
pgGetGqlInputTypeByTypeIdAndModifier,
pgSql: sql,
gql2pg,
graphql: {
GraphQLObjectType,
GraphQLInputObjectType,
GraphQLNonNull,
GraphQLString,
},
pgColumnFilter,
inflection,
pgQueryFromResolveData: queryFromResolveData,
pgOmit: omit,
pgViaTemporaryTable: viaTemporaryTable,
describePgEntity,
sqlCommentByAddingTags,
pgField,
} = build;
const {
scope: { isRootMutation },
fieldWithHooks,
} = context;
if (!isRootMutation) {
return fields;
}
return extend(
fields,
pgIntrospectionResultsByKind.class.reduce((memo, table) => {
// PERFORMANCE: These used to be .filter(...) calls
if (!table.namespace) return memo;
if (!table.isSelectable) return memo;
if (!table.isInsertable || omit(table, "create")) return memo;
const Table = pgGetGqlTypeByTypeIdAndModifier(table.type.id, null);
if (!Table) {
debug(
`There was no table type for table '${table.namespace.name}.${table.name}', so we're not generating a create mutation for it.`
);
return memo;
}
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.`
);
}
const tableTypeName = inflection.tableType(table);
const InputType = newWithHooks(
GraphQLInputObjectType,
{
name: inflection.createInputType(table),
description: build.wrapDescription(
`All input for the create \`${tableTypeName}\` mutation.`,
"type"
),
fields: {
clientMutationId: {
description: build.wrapDescription(
"An arbitrary string value with no semantic meaning. Will be included in the payload verbatim. May be used to track mutations by the client.",
"field"
),
type: GraphQLString,
},
...(TableInput
? {
[inflection.tableFieldName(table)]: {
description: build.wrapDescription(
`The \`${tableTypeName}\` to be created by this mutation.`,
"field"
),
type: new GraphQLNonNull(TableInput),
},
}
: null),
},
},
{
__origin: `Adding 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, // TODO:v5: remove - TYPO!
pgIntrospection: table,
}
);
const PayloadType = newWithHooks(
GraphQLObjectType,
{
name: inflection.createPayloadType(table),
description: build.wrapDescription(
`The output of our create \`${tableTypeName}\` mutation.`,
"type"
),
fields: ({ fieldWithHooks }) => {
const tableName = inflection.tableFieldName(table);
return {
clientMutationId: {
description: build.wrapDescription(
"The exact same `clientMutationId` that was provided in the mutation input, unchanged and unused. May be used by a client to track mutations.",
"field"
),
type: GraphQLString,
},
[tableName]: pgField(
build,
fieldWithHooks,
tableName,
{
description: build.wrapDescription(
`The \`${tableTypeName}\` that was created by this mutation.`,
"field"
),
type: Table,
},
{
isPgCreatePayloadResultField: true,
pgFieldIntrospection: table,
}
),
};
},
},
{
__origin: `Adding table 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 fieldName = inflection.createField(table);
memo = build.extend(
memo,
{
[fieldName]: fieldWithHooks(
fieldName,
context => {
const { getDataFromParsedResolveInfoFragment } = context;
const relevantAttributes = table.attributes.filter(
attr =>
pgColumnFilter(attr, build, context) &&
!omit(attr, "create")
);
return {
description: build.wrapDescription(
`Creates a single \`${tableTypeName}\`.`,
"field"
),
type: PayloadType,
args: {
input: {
type: new GraphQLNonNull(InputType),
},
},
async resolve(data, args, resolveContext, resolveInfo) {
const { input } = args;
const { pgClient } = resolveContext;
const parsedResolveInfoFragment = parseResolveInfo(
resolveInfo
);
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 = [];
const sqlValues = [];
const inputData = input[inflection.tableFieldName(table)];
relevantAttributes.forEach(attr => {
const fieldName = inflection.column(attr);
const val = inputData[fieldName];
if (
Object.prototype.hasOwnProperty.call(
inputData,
fieldName
)
) {
sqlColumns.push(sql.identifier(attr.name));
sqlValues.push(
gql2pg(val, attr.type, attr.typeModifier)
);
}
});
const mutationQuery = sql.query`\
insert into ${sql.identifier(table.namespace.name, table.name)} ${
sqlColumns.length
? sql.fragment`(${sql.join(
sqlColumns,
", "
)}) values(${sql.join(sqlValues, ", ")})`
: sql.fragment`default values`
} returning *`;
let row;
try {
await pgClient.query("SAVEPOINT graphql_mutation");
const rows = await viaTemporaryTable(
pgClient,
sql.identifier(table.namespace.name, table.name),
mutationQuery,
insertedRowAlias,
query
);
row = rows[0];
await pgClient.query(
"RELEASE SAVEPOINT graphql_mutation"
);
} catch (e) {
await pgClient.query(
"ROLLBACK TO SAVEPOINT graphql_mutation"
);
throw e;
}
return {
clientMutationId: input.clientMutationId,
data: row,
};
},
};
},
{
pgFieldIntrospection: table,
isPgCreateMutationField: true,
}
),
},
`Adding create mutation for ${describePgEntity(
table
)}. You can omit this default mutation with a 'Smart Comment':\n\n ${sqlCommentByAddingTags(
table,
{
omit: "create",
}
)}`
);
return memo;
}, {}),
`Adding default 'create' mutation to root mutation`
);
},
["PgMutationCreate"],
[],
["PgTables"]
);
}: Plugin);