Between GROQ and a hard place
Custom functions
Log in to watch a video walkthrough of this lesson
Log in

Reduce code duplication by including custom functions in your GROQ queries.
Log in to mark your progress for each Lesson and Task
For advanced use cases where you need to regularly perform the same transformation it is also possible to write custom GROQ functions.
This is especially useful for complex schema types where you want to return the same attributes for different fields. For example resolving images or references the same way.
In the example below, both the headline
and venue
reference are passed into the same function which will resolve the reference and return the name
attribute.
Resolve artist and venue references with the same custom function
fn learn::reference($doc) = $doc->{name};
*[_type == "event"]{ "headline": learn::reference(headline), "venue": learn::reference(venue)}
This is a marked improvement from string interpolation with strings and variables in JavaScript and should result in shorter queries overall.
See GROQ Custom Functions in the documentation for additional notes and limitations
You have 1 uncompleted task in this lesson
0 of 1