Skip to content

Commit 04ceeab

Browse files
dudobenjie
andauthored
Update make-extend-schema-plugin.md (#357)
Co-authored-by: Benjie <benjie@jemjie.com>
1 parent 3e547e2 commit 04ceeab

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

src/pages/postgraphile/make-extend-schema-plugin.md

+63
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,69 @@ const MyRegisterUserMutationPlugin = makeExtendSchemaPlugin(build => {
535535
Note that the `@pgField` directive here is necessary for PostGraphile to "look
536536
ahead" and determine what to request from the database.
537537

538+
#### Working with arrays via `json_array_elements`
539+
540+
Here's an example of working with a join table, and bulk inserting multiple records from a GraphQL list.
541+
542+
```js
543+
...
544+
545+
typeDefs: gql`
546+
input UpdatePersonsThingsInput {
547+
personId: UUID!,
548+
thingIds: [UUID!]!
549+
}
550+
type UpdatePersonThingsPayload {
551+
personThings: [PersonThing!]
552+
}
553+
extend type Mutation {
554+
updatePersonsThings(input: UpdatePersonsThingsInput!): UpdatePersonsThingsPayload
555+
}
556+
`,
557+
resolvers: {
558+
Mutation: {
559+
updatePersonsThings: async (_query, { input: { personId, thingIds } }, { pgClient }, _resolveInfo) => {
560+
await pgClient.query("SAVEPOINT graphql_mutation");
561+
try {
562+
// Ensure proper formatting. This may not be necessary if not modifying the input
563+
const elements = JSON.stringify(thingIds.map(thingId => ({ thingId, personId })));
564+
565+
// Bulk insert
566+
const { rows } = await pgClient.query(`
567+
INSERT INTO public.persons_things (person_id, thing_id)
568+
SELECT
569+
(el->>'personId')::uuid,
570+
(el->>'thingId')::uuid
571+
FROM json_array_elements($1::json) el
572+
RETURNING id
573+
`, [elements]);
574+
575+
// Return data for next layer to use
576+
return { personThingIds: rows.map(({ id }) => id) };
577+
} catch (e) {
578+
await pgClient.query("ROLLBACK TO SAVEPOINT graphql_mutation");
579+
console.error(e);
580+
throw e;
581+
} finally {
582+
await pgClient.query("RELEASE SAVEPOINT graphql_mutation");
583+
}
584+
},
585+
},
586+
UpdatePersonThingsPayload: {
587+
personThings: ({ personThingIds }, _args, _context, { graphile: { selectGraphQLResultFromTable } }) => {
588+
return selectGraphQLResultFromTable(
589+
sql.fragment`public.persons_things`,
590+
(tableAlias, queryBuilder) => {
591+
queryBuilder.where(
592+
sql.fragment`${tableAlias}.id = ANY (${sql.value(personThingIds)}::int[])`
593+
);
594+
}
595+
);
596+
}
597+
}
598+
}
599+
```
600+
538601
### Mutation Example with Node ID
539602

540603
In this example we'll use a GraphQL Global Object Identifier (aka Node ID) to

0 commit comments

Comments
 (0)