Sitecore GraphQL — Upserting Items
The new GraphQL API that is shipped as part of the Sitecore Headless Services offering from Sitecore is a game changer. It is a replacement for the decades old Item Rest API. For new development I’d highly recommend it. A good starting point to get your head around it: https://graphql.org/learn/
It comes with GraphQL mutations to create, update, and delete items. And of course querying items directly, as well as querying via the search indexes. In my case I wanted to be able to continuously create / update items which may or may not already exist. This is acheivable by doing a query/search for the existing item and then either call create / update as necessary. But why not cut out the middleman and add an upsert function which can do that hard work for us?
Step 1: Some code.
I decompiled the Sitecore.Services.GraphQL.Content.Mutations.CreateItemMutation
and the Sitecore.Services.GraphQL.Content.Mutations.UpdateItemMutation
and put it together like this:
Step 2: Try it out
Sitecore Headless also ships with the GraphQL UI Playground where you can send your queries https://sc.dev.local/sitecore/api/graph/items/master/ui
It generates all the schema docs automatically. So after deploying our new mutation — here it is ready to use!