FormidableLabs / nextjs-sanity-fe

NextJS Demo site with Sanity CMS
https://nextjs-sanity.formidable.dev/
29 stars 6 forks source link

PoC: Strongly-typed schema #201

Closed scottrippey closed 10 months ago

scottrippey commented 11 months ago

GroqD currently supports strongly-typed output types.
However, it is completely unaware of the input types as defined in the Sanity Schema.

Here are some tasks for creating a POC for strongly-typed input types:

API methods to make strongly-typed:

scottrippey commented 11 months ago

Key Findings from PoC

A PoC was created in this branch: sanity-typed This implemented several of the API methods above, making them strongly typed according to the Sanity Schema. Here are my conclusions about this approach.

API changes to support strong types

I was able to leave the GroqD API intact, with only 2 notable changes

Effectiveness of this API

For the most part, strongly-typed schema gives a GREAT developer experience!

Performance

This might be a prohibiting factor.

Workarounds

The shape of the inferred schema is pretty basic:

Simplified Example Schema ```ts export type SanitySchemaCompiled = { category: { slug: { _type: "slug"; current: string }; name: string; description: string; }; product: { slug: { _type: "slug"; current: string }; name: string; description: string; categories?: Array<{ _type: "reference"; _ref: string; [_referenced]: "category"; }>; }; }; ```
Massive Performance Improvement by listing documents Instead of inferring all types from the entire `config`, we can infer the exact same type by manually listing all document types. This can live adjacent to our config itself, making it easy to maintain if types were added / removed. ```ts // export type SanitySchema = InferSchemaValues; export type SanitySchema = { category: InferRawValue; categoryImage: InferRawValue; description: InferRawValue; flavour: InferRawValue; product: InferRawValue; productImage: InferRawValue; siteSettings: InferRawValue; style: InferRawValue; variant: InferRawValue; }; ```

Follow-up tasks

After working through this PoC, Grant and I had a discussion that led to an interesting conclusion.

So, this conclusion is leading us to a follow-up PoC -- making Zod optional/swappable, and relying on Schema types and static type checks instead of runtime checks! See #202.

scottrippey commented 10 months ago

Update: this has been implemented as the groq-builder package in groqd