Lesson
4
Adapting a front end without downtime
Prepare a front end for down-time-less content migration by adapting a GROQ query with coalesce()
Log in to mark your progress for each Lesson and Task
Let’s say that we want to do this schema and content migration without any downtime and without disrupting the work of content creators. Before deploying the change to the Studio, you can deploy a small change to the front end that makes it ready to use the new field and fall back on the old field if there is no content. In other words, this is how the workflow could look like:
- Make the content query work with content for both fields
- Deploy the frontend change
- Deploy the Studio with the deprecated and new fields
- Run a content migration to move legacy content over to the new field
- Adapt the content query to remove the assumption of the old field
This may seem like a lot, but it should be fairly straightforward in this case.
In this exercise, we will use the front end code from the Day One with Sanity Studio course.
Open the front end you made in the Day One course module.
You must only change the query to make the front end work with content from both fields: eventType
and format
.
Locate the GROQ query for the single event route.
const EVENT_QUERY = `*[ _type == "event" && slug.current == $slug][0]{ ..., headline->, venue->}`;
In this query, you use the ellipsis (…
) as a quick way to return all the fields on the document, and then below, you’re “overriding” the headline
and venue
reference fields with the join operator (→
) to access all the fields of these documents. This is just a quick way to get all the data into the application and start experimenting with it. For projects in production, you would usually specify all the fields you use to prevent overfetching.
Now you want to override the eventType
data to ensure we always get data for it, regardless if the deprecated or new field is used. To do this, you can use a GROQ function called coalesce()
Update the query with the
coalesce()
functionconst EVENT_QUERY = `*[ _type == "event" && slug.current == $slug][0]{ ..., "eventType": coalesce(format, eventType), headline->, venue->}`;
What this query does now is to first look for a value for format
and set that to the eventType
key, if it doesn’t find a value for it, it will fallback on the value for eventType
.
Confirm that the query works by setting a value for “Event format” on an event that’s different from the “Event type”
Now, your front end and your new Studio schema changes can be deployed (you don’t have to for this course) without any downtime. Your content creators can start working with the new Event format field, while they cannot change the old Event type field.
You have 4 uncompleted tasks in this lesson
0 of 4