Unverified Commit cb60718b authored by Cody Olsen's avatar Cody Olsen Committed by GitHub

Add TypeGen to Sanity example (#64198)

Adds support for the [newly introduced Sanity
TypeGen](https://www.sanity.io/blog/introducing-sanity-typegen)! 🥳
parent c9c074c1
...@@ -4,6 +4,7 @@ node_modules ...@@ -4,6 +4,7 @@ node_modules
**/.vscode/** **/.vscode/**
**/dist/** **/dist/**
e2e-tests/** e2e-tests/**
examples/cms-sanity/sanity.types.ts
examples/with-eslint/** examples/with-eslint/**
examples/with-typescript-eslint-jest/** examples/with-typescript-eslint-jest/**
examples/with-kea/** examples/with-kea/**
......
# Ignoring generated files
./sanity.types.ts
# Ignoring generated files
./sanity.types.ts
./schema.json
...@@ -9,6 +9,7 @@ The Studio connects to Sanity Content Lake, which gives you hosted content APIs ...@@ -9,6 +9,7 @@ The Studio connects to Sanity Content Lake, which gives you hosted content APIs
## Features ## Features
- A performant, static blog with editable posts, authors, and site settings - A performant, static blog with editable posts, authors, and site settings
- TypeScript setup with [Sanity TypeGen](https://www.sanity.io/docs/sanity-typegen)
- A native and customizable authoring environment, accessible on `yourblog.com/studio` - A native and customizable authoring environment, accessible on `yourblog.com/studio`
- Real-time and collaborative content editing with fine-grained revision history - Real-time and collaborative content editing with fine-grained revision history
- Side-by-side instant content preview that works across your whole site - Side-by-side instant content preview that works across your whole site
...@@ -44,6 +45,12 @@ yarn create next-app --example cms-sanity next-sanity-blog ...@@ -44,6 +45,12 @@ yarn create next-app --example cms-sanity next-sanity-blog
pnpm create next-app --example cms-sanity next-sanity-blog pnpm create next-app --example cms-sanity next-sanity-blog
``` ```
Whenever you edit a GROQ query you update the TypeScript types by running:
```bash
npm run typegen
```
# Configuration # Configuration
- [Step 1. Set up the environment](#step-1-set-up-the-environment) - [Step 1. Set up the environment](#step-1-set-up-the-environment)
......
import { Image } from "next-sanity/image"; import { Image } from "next-sanity/image";
import { Author } from "@/sanity/lib/queries"; import type { Author } from "@/sanity.types";
import { urlForImage } from "@/sanity/lib/utils"; import { urlForImage } from "@/sanity/lib/utils";
export default function Avatar({ name, picture }: Author) { interface Props {
name: string;
picture: Exclude<Author["picture"], undefined> | null;
}
export default function Avatar({ name, picture }: Props) {
return ( return (
<div className="flex items-center text-xl"> <div className="flex items-center text-xl">
{picture?.asset?._ref ? ( {picture?.asset?._ref ? (
......
import "../globals.css"; import "../globals.css";
import { SpeedInsights } from "@vercel/speed-insights/next"; import { SpeedInsights } from "@vercel/speed-insights/next";
import { Metadata } from "next"; import type { Metadata } from "next";
import { PortableTextBlock, VisualEditing, toPlainText } from "next-sanity"; import {
VisualEditing,
toPlainText,
type PortableTextBlock,
} from "next-sanity";
import { Inter } from "next/font/google"; import { Inter } from "next/font/google";
import { draftMode } from "next/headers"; import { draftMode } from "next/headers";
import { Suspense } from "react"; import { Suspense } from "react";
...@@ -10,13 +14,14 @@ import { Suspense } from "react"; ...@@ -10,13 +14,14 @@ import { Suspense } from "react";
import AlertBanner from "./alert-banner"; import AlertBanner from "./alert-banner";
import PortableText from "./portable-text"; import PortableText from "./portable-text";
import type { SettingsQueryResult } from "@/sanity.types";
import * as demo from "@/sanity/lib/demo"; import * as demo from "@/sanity/lib/demo";
import { sanityFetch } from "@/sanity/lib/fetch"; import { sanityFetch } from "@/sanity/lib/fetch";
import { SettingsQueryResponse, settingsQuery } from "@/sanity/lib/queries"; import { settingsQuery } from "@/sanity/lib/queries";
import { resolveOpenGraphImage } from "@/sanity/lib/utils"; import { resolveOpenGraphImage } from "@/sanity/lib/utils";
export async function generateMetadata(): Promise<Metadata> { export async function generateMetadata(): Promise<Metadata> {
const settings = await sanityFetch<SettingsQueryResponse>({ const settings = await sanityFetch<SettingsQueryResult>({
query: settingsQuery, query: settingsQuery,
// Metadata should never contain stega // Metadata should never contain stega
stega: false, stega: false,
...@@ -53,10 +58,10 @@ const inter = Inter({ ...@@ -53,10 +58,10 @@ const inter = Inter({
}); });
async function Footer() { async function Footer() {
const data = await sanityFetch<SettingsQueryResponse>({ const data = await sanityFetch<SettingsQueryResult>({
query: settingsQuery, query: settingsQuery,
}); });
const footer = data?.footer || ([] as PortableTextBlock[]); const footer = data?.footer || [];
return ( return (
<footer className="bg-accent-1 border-accent-2 border-t"> <footer className="bg-accent-1 border-accent-2 border-t">
...@@ -64,7 +69,7 @@ async function Footer() { ...@@ -64,7 +69,7 @@ async function Footer() {
{footer.length > 0 ? ( {footer.length > 0 ? (
<PortableText <PortableText
className="prose-sm text-pretty bottom-0 w-full max-w-none bg-white py-12 text-center md:py-20" className="prose-sm text-pretty bottom-0 w-full max-w-none bg-white py-12 text-center md:py-20"
value={footer} value={footer as PortableTextBlock[]}
/> />
) : ( ) : (
<div className="flex flex-col items-center py-28 lg:flex-row"> <div className="flex flex-col items-center py-28 lg:flex-row">
......
...@@ -4,17 +4,15 @@ import Avatar from "./avatar"; ...@@ -4,17 +4,15 @@ import Avatar from "./avatar";
import CoverImage from "./cover-image"; import CoverImage from "./cover-image";
import DateComponent from "./date"; import DateComponent from "./date";
import type { MoreStoriesQueryResult } from "@/sanity.types";
import { sanityFetch } from "@/sanity/lib/fetch"; import { sanityFetch } from "@/sanity/lib/fetch";
import { import { moreStoriesQuery } from "@/sanity/lib/queries";
MoreStoriesQueryResponse,
moreStoriesQuery,
} from "@/sanity/lib/queries";
export default async function MoreStories(params: { export default async function MoreStories(params: {
skip: string; skip: string;
limit: number; limit: number;
}) { }) {
const data = await sanityFetch<MoreStoriesQueryResponse>({ const data = await sanityFetch<MoreStoriesQueryResult>({
query: moreStoriesQuery, query: moreStoriesQuery,
params, params,
}); });
......
...@@ -8,15 +8,10 @@ import MoreStories from "./more-stories"; ...@@ -8,15 +8,10 @@ import MoreStories from "./more-stories";
import Onboarding from "./onboarding"; import Onboarding from "./onboarding";
import PortableText from "./portable-text"; import PortableText from "./portable-text";
import type { HeroQueryResult, SettingsQueryResult } from "@/sanity.types";
import * as demo from "@/sanity/lib/demo"; import * as demo from "@/sanity/lib/demo";
import { sanityFetch } from "@/sanity/lib/fetch"; import { sanityFetch } from "@/sanity/lib/fetch";
import { import { heroQuery, settingsQuery } from "@/sanity/lib/queries";
HeroQueryResponse,
Post,
SettingsQueryResponse,
heroQuery,
settingsQuery,
} from "@/sanity/lib/queries";
function Intro(props: { title: string | null | undefined; description: any }) { function Intro(props: { title: string | null | undefined; description: any }) {
const title = props.title || demo.title; const title = props.title || demo.title;
...@@ -46,7 +41,7 @@ function HeroPost({ ...@@ -46,7 +41,7 @@ function HeroPost({
date, date,
author, author,
}: Pick< }: Pick<
Post, Exclude<HeroQueryResult, null>,
"title" | "coverImage" | "date" | "excerpt" | "author" | "slug" "title" | "coverImage" | "date" | "excerpt" | "author" | "slug"
>) { >) {
return ( return (
...@@ -80,10 +75,10 @@ function HeroPost({ ...@@ -80,10 +75,10 @@ function HeroPost({
export default async function Page() { export default async function Page() {
const [settings, heroPost] = await Promise.all([ const [settings, heroPost] = await Promise.all([
sanityFetch<SettingsQueryResponse>({ sanityFetch<SettingsQueryResult>({
query: settingsQuery, query: settingsQuery,
}), }),
sanityFetch<HeroQueryResponse>({ query: heroQuery }), sanityFetch<HeroQueryResult>({ query: heroQuery }),
]); ]);
return ( return (
......
import type { Metadata, ResolvingMetadata } from "next"; import type { Metadata, ResolvingMetadata } from "next";
import { groq } from "next-sanity"; import { groq, type PortableTextBlock } from "next-sanity";
import Link from "next/link"; import Link from "next/link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Suspense } from "react"; import { Suspense } from "react";
...@@ -10,33 +10,36 @@ import DateComponent from "../../date"; ...@@ -10,33 +10,36 @@ import DateComponent from "../../date";
import MoreStories from "../../more-stories"; import MoreStories from "../../more-stories";
import PortableText from "../../portable-text"; import PortableText from "../../portable-text";
import type {
PostQueryResult,
PostSlugsResult,
SettingsQueryResult,
} from "@/sanity.types";
import * as demo from "@/sanity/lib/demo";
import { sanityFetch } from "@/sanity/lib/fetch"; import { sanityFetch } from "@/sanity/lib/fetch";
import { import { postQuery, settingsQuery } from "@/sanity/lib/queries";
PostQueryResponse,
SettingsQueryResponse,
postQuery,
settingsQuery,
} from "@/sanity/lib/queries";
import { resolveOpenGraphImage } from "@/sanity/lib/utils"; import { resolveOpenGraphImage } from "@/sanity/lib/utils";
import * as demo from "@/sanity/lib/demo";
type Props = { type Props = {
params: { slug: string }; params: { slug: string };
}; };
const postSlugs = groq`*[_type == "post"]{slug}`;
export async function generateStaticParams() { export async function generateStaticParams() {
return sanityFetch<{ slug: string }[]>({ const params = await sanityFetch<PostSlugsResult>({
query: groq`*[_type == "post" && defined(slug.current)]{"slug": slug.current}`, query: postSlugs,
perspective: "published", perspective: "published",
stega: false, stega: false,
}); });
return params.map(({ slug }) => ({ slug: slug?.current }));
} }
export async function generateMetadata( export async function generateMetadata(
{ params }: Props, { params }: Props,
parent: ResolvingMetadata, parent: ResolvingMetadata,
): Promise<Metadata> { ): Promise<Metadata> {
const post = await sanityFetch<PostQueryResponse>({ const post = await sanityFetch<PostQueryResult>({
query: postQuery, query: postQuery,
params, params,
stega: false, stega: false,
...@@ -56,11 +59,11 @@ export async function generateMetadata( ...@@ -56,11 +59,11 @@ export async function generateMetadata(
export default async function PostPage({ params }: Props) { export default async function PostPage({ params }: Props) {
const [post, settings] = await Promise.all([ const [post, settings] = await Promise.all([
sanityFetch<PostQueryResponse>({ sanityFetch<PostQueryResult>({
query: postQuery, query: postQuery,
params, params,
}), }),
sanityFetch<SettingsQueryResponse>({ sanityFetch<SettingsQueryResult>({
query: settingsQuery, query: settingsQuery,
}), }),
]); ]);
...@@ -101,7 +104,10 @@ export default async function PostPage({ params }: Props) { ...@@ -101,7 +104,10 @@ export default async function PostPage({ params }: Props) {
</div> </div>
</div> </div>
{post.content?.length && ( {post.content?.length && (
<PortableText className="mx-auto max-w-2xl" value={post.content} /> <PortableText
className="mx-auto max-w-2xl"
value={post.content as PortableTextBlock[]}
/>
)} )}
</article> </article>
<aside> <aside>
......
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"predev": "npm run typegen",
"dev": "next", "dev": "next",
"prebuild": "npm run typegen",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "next lint",
"presetup": "echo 'about to setup env variables, follow the guide here: https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#using-the-sanity-cli'", "presetup": "echo 'about to setup env variables, follow the guide here: https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#using-the-sanity-cli'",
"setup": "npx sanity@latest init --env .env.local", "setup": "npx sanity@latest init --env .env.local",
"postsetup": "echo 'create the read token by following the rest of the guide: https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#creating-a-read-token'" "postsetup": "echo 'create the read token by following the rest of the guide: https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#creating-a-read-token'",
"typegen": "sanity schema extract && sanity typegen generate"
}, },
"dependencies": { "dependencies": {
"@sanity/assist": "^2.0.4", "@sanity/assist": "3.0.3",
"@sanity/icons": "^2.11.2", "@sanity/icons": "2.11.8",
"@sanity/image-url": "^1.0.2", "@sanity/image-url": "1.0.2",
"@sanity/preview-url-secret": "^1.6.5", "@sanity/preview-url-secret": "1.6.7",
"@sanity/vision": "^3.35.0", "@sanity/vision": "3.37.2",
"@tailwindcss/typography": "^0.5.10", "@tailwindcss/typography": "^0.5.12",
"@types/node": "^20.11.30", "@types/node": "^20.12.7",
"@types/react": "^18.2.67", "@types/react": "^18.2.75",
"@types/react-dom": "^18.2.22", "@types/react-dom": "^18.2.24",
"@vercel/speed-insights": "^1.0.10", "@vercel/speed-insights": "^1.0.10",
"autoprefixer": "^10.4.18", "autoprefixer": "^10.4.19",
"date-fns": "^3.6.0", "date-fns": "^3.6.0",
"next": "latest", "next": "latest",
"next-sanity": "^8.4.4", "next-sanity": "9.0.0",
"postcss": "^8.4.37", "postcss": "^8.4.38",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
"sanity": "^3.35.0", "sanity": "3.37.2",
"sanity-plugin-asset-source-unsplash": "^2.0.1", "sanity-plugin-asset-source-unsplash": "3.0.0",
"server-only": "^0.0.1", "server-only": "^0.0.1",
"styled-components": "^6.1.8", "styled-components": "6.1.8",
"tailwindcss": "^3.4.1", "tailwindcss": "^3.4.3",
"typescript": "5.4.2" "typescript": "5.4.5"
}, },
"devDependencies": { "devDependencies": {
"@next/env": "latest", "@next/env": "latest",
......
{
"path": "'./{app,sanity}/**/*.{ts,tsx,js,jsx}'"
}
This diff is collapsed.
import { groq, type PortableTextBlock } from "next-sanity"; import { groq } from "next-sanity";
import type { Image } from "sanity";
export const settingsQuery = groq`*[_type == "settings"][0]`; export const settingsQuery = groq`*[_type == "settings"][0]`;
export interface SettingsQueryResponse {
title?: string;
description?: PortableTextBlock[];
footer?: PortableTextBlock[];
ogImage?: (Image & { alt?: string; metadataBase?: string }) | null;
}
export interface Author { const postFields = /* groq */ `
name: string;
picture?: (Image & { alt?: string | null }) | null;
}
export interface Post {
_id: string;
status: "draft" | "published";
title: string;
slug: string;
excerpt?: string | null;
coverImage?: (Image & { alt?: string }) | null;
date: string;
author?: Author | null;
}
const postFields = groq`
_id, _id,
"status": select(_originalId in path("drafts.**") => "draft", "published"), "status": select(_originalId in path("drafts.**") => "draft", "published"),
"title": coalesce(title, "Untitled"), "title": coalesce(title, "Untitled"),
...@@ -39,23 +17,12 @@ export const heroQuery = groq`*[_type == "post" && defined(slug.current)] | orde ...@@ -39,23 +17,12 @@ export const heroQuery = groq`*[_type == "post" && defined(slug.current)] | orde
content, content,
${postFields} ${postFields}
}`; }`;
export type HeroQueryResponse =
| (Post & {
content?: PortableTextBlock[] | null;
})
| null;
export const moreStoriesQuery = groq`*[_type == "post" && _id != $skip && defined(slug.current)] | order(date desc, _updatedAt desc) [0...$limit] { export const moreStoriesQuery = groq`*[_type == "post" && _id != $skip && defined(slug.current)] | order(date desc, _updatedAt desc) [0...$limit] {
${postFields} ${postFields}
}`; }`;
export type MoreStoriesQueryResponse = Post[] | null;
export const postQuery = groq`*[_type == "post" && slug.current == $slug] [0] { export const postQuery = groq`*[_type == "post" && slug.current == $slug] [0] {
content, content,
${postFields} ${postFields}
}`; }`;
export type PostQueryResponse =
| (Post & {
content?: PortableTextBlock[] | null;
})
| null;
This diff is collapsed.
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5", "target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": true, "strict": true,
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"noEmit": true, "noEmit": true,
"esModuleInterop": true, // Use module: preserve, and remove moduleResolution, esModuleInterop and resolveJsonModule once Next ships support
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "bundler",
"esModuleInterop": true,
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment