Validate GROQ query for better debugging in sanityClient.fetch wrapper

2 replies
Last updated: Dec 9, 2020
Is there any library to validate a groq query? Creating a functional wrapper for
sanityClient.fetch
, and would be cool to have better debugging. πŸ™‚
AI Update

Great question! There are actually several tools and libraries you can use to validate GROQ queries and improve your debugging experience:

groq-js - The Core Validation Library

groq-js is the official JavaScript parser and implementation for GROQ. It's perfect for what you're trying to do - you can use it to parse and validate GROQ queries before sending them to the Sanity API. This helps catch syntax errors early in development and gives you better error messages for debugging.

The library lets you parse GROQ query strings to check their validity, making it ideal for wrapping around sanityClient.fetch() to add validation and improved debugging capabilities.

VS Code Extension for Development

The Sanity VS Code extension provides syntax highlighting and IntelliSense for GROQ queries directly in your editor. It works when you use the defineQuery function from next-sanity or the groq template literal, and you can even execute queries right from VS Code to see results immediately.

TypeScript Type Safety with groqd

If you're using TypeScript, groqd is a community library that provides schema validation and query building with full type safety. It generates TypeScript types from your GROQ queries and validates results at runtime, which can catch issues that pure syntax validation might miss.

Native TypeGen Approach

Alternatively, Sanity's built-in TypeGen can generate TypeScript types for your queries when you wrap them with defineQuery. This gives you compile-time validation and autocomplete, which catches many query issues before runtime.

The Vision Tool

Don't forget about the Vision plugin (usually available at /vision in your Studio) - it's a GROQ playground where you can test and debug queries interactively with real data from your dataset.

For your functional wrapper around sanityClient.fetch, I'd recommend starting with groq-js for validation and pairing it with defineQuery and TypeGen for type safety. This combo gives you both runtime validation and compile-time checking! πŸ™‚

Show original thread
2 replies
You can at least parse a groq query with
groq-js
Β . I don't think it return very useful debugging info yet, but you can at least capture if it's valid.
Awesome, thanks for this! πŸ™‚ It's at least some more info to be able to say if it's valid or not.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?