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
**/.vscode/**
**/dist/**
e2e-tests/**
examples/cms-sanity/sanity.types.ts
examples/with-eslint/**
examples/with-typescript-eslint-jest/**
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
## Features
- 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`
- Real-time and collaborative content editing with fine-grained revision history
- 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
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
- [Step 1. Set up the environment](#step-1-set-up-the-environment)
......
import { Image } from "next-sanity/image";
import { Author } from "@/sanity/lib/queries";
import type { Author } from "@/sanity.types";
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 (
<div className="flex items-center text-xl">
{picture?.asset?._ref ? (
......
import "../globals.css";
import { SpeedInsights } from "@vercel/speed-insights/next";
import { Metadata } from "next";
import { PortableTextBlock, VisualEditing, toPlainText } from "next-sanity";
import type { Metadata } from "next";
import {
VisualEditing,
toPlainText,
type PortableTextBlock,
} from "next-sanity";
import { Inter } from "next/font/google";
import { draftMode } from "next/headers";
import { Suspense } from "react";
......@@ -10,13 +14,14 @@ import { Suspense } from "react";
import AlertBanner from "./alert-banner";
import PortableText from "./portable-text";
import type { SettingsQueryResult } from "@/sanity.types";
import * as demo from "@/sanity/lib/demo";
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";
export async function generateMetadata(): Promise<Metadata> {
const settings = await sanityFetch<SettingsQueryResponse>({
const settings = await sanityFetch<SettingsQueryResult>({
query: settingsQuery,
// Metadata should never contain stega
stega: false,
......@@ -53,10 +58,10 @@ const inter = Inter({
});
async function Footer() {
const data = await sanityFetch<SettingsQueryResponse>({
const data = await sanityFetch<SettingsQueryResult>({
query: settingsQuery,
});
const footer = data?.footer || ([] as PortableTextBlock[]);
const footer = data?.footer || [];
return (
<footer className="bg-accent-1 border-accent-2 border-t">
......@@ -64,7 +69,7 @@ async function Footer() {
{footer.length > 0 ? (
<PortableText
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">
......
......@@ -4,17 +4,15 @@ import Avatar from "./avatar";
import CoverImage from "./cover-image";
import DateComponent from "./date";
import type { MoreStoriesQueryResult } from "@/sanity.types";
import { sanityFetch } from "@/sanity/lib/fetch";
import {
MoreStoriesQueryResponse,
moreStoriesQuery,
} from "@/sanity/lib/queries";
import { moreStoriesQuery } from "@/sanity/lib/queries";
export default async function MoreStories(params: {
skip: string;
limit: number;
}) {
const data = await sanityFetch<MoreStoriesQueryResponse>({
const data = await sanityFetch<MoreStoriesQueryResult>({
query: moreStoriesQuery,
params,
});
......
......@@ -8,15 +8,10 @@ import MoreStories from "./more-stories";
import Onboarding from "./onboarding";
import PortableText from "./portable-text";
import type { HeroQueryResult, SettingsQueryResult } from "@/sanity.types";
import * as demo from "@/sanity/lib/demo";
import { sanityFetch } from "@/sanity/lib/fetch";
import {
HeroQueryResponse,
Post,
SettingsQueryResponse,
heroQuery,
settingsQuery,
} from "@/sanity/lib/queries";
import { heroQuery, settingsQuery } from "@/sanity/lib/queries";
function Intro(props: { title: string | null | undefined; description: any }) {
const title = props.title || demo.title;
......@@ -46,7 +41,7 @@ function HeroPost({
date,
author,
}: Pick<
Post,
Exclude<HeroQueryResult, null>,
"title" | "coverImage" | "date" | "excerpt" | "author" | "slug"
>) {
return (
......@@ -80,10 +75,10 @@ function HeroPost({
export default async function Page() {
const [settings, heroPost] = await Promise.all([
sanityFetch<SettingsQueryResponse>({
sanityFetch<SettingsQueryResult>({
query: settingsQuery,
}),
sanityFetch<HeroQueryResponse>({ query: heroQuery }),
sanityFetch<HeroQueryResult>({ query: heroQuery }),
]);
return (
......
import type { Metadata, ResolvingMetadata } from "next";
import { groq } from "next-sanity";
import { groq, type PortableTextBlock } from "next-sanity";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Suspense } from "react";
......@@ -10,33 +10,36 @@ import DateComponent from "../../date";
import MoreStories from "../../more-stories";
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 {
PostQueryResponse,
SettingsQueryResponse,
postQuery,
settingsQuery,
} from "@/sanity/lib/queries";
import { postQuery, settingsQuery } from "@/sanity/lib/queries";
import { resolveOpenGraphImage } from "@/sanity/lib/utils";
import * as demo from "@/sanity/lib/demo";
type Props = {
params: { slug: string };
};
const postSlugs = groq`*[_type == "post"]{slug}`;
export async function generateStaticParams() {
return sanityFetch<{ slug: string }[]>({
query: groq`*[_type == "post" && defined(slug.current)]{"slug": slug.current}`,
const params = await sanityFetch<PostSlugsResult>({
query: postSlugs,
perspective: "published",
stega: false,
});
return params.map(({ slug }) => ({ slug: slug?.current }));
}
export async function generateMetadata(
{ params }: Props,
parent: ResolvingMetadata,
): Promise<Metadata> {
const post = await sanityFetch<PostQueryResponse>({
const post = await sanityFetch<PostQueryResult>({
query: postQuery,
params,
stega: false,
......@@ -56,11 +59,11 @@ export async function generateMetadata(
export default async function PostPage({ params }: Props) {
const [post, settings] = await Promise.all([
sanityFetch<PostQueryResponse>({
sanityFetch<PostQueryResult>({
query: postQuery,
params,
}),
sanityFetch<SettingsQueryResponse>({
sanityFetch<SettingsQueryResult>({
query: settingsQuery,
}),
]);
......@@ -101,7 +104,10 @@ export default async function PostPage({ params }: Props) {
</div>
</div>
{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>
<aside>
......
{
"private": true,
"scripts": {
"predev": "npm run typegen",
"dev": "next",
"prebuild": "npm run typegen",
"build": "next build",
"start": "next start",
"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'",
"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": {
"@sanity/assist": "^2.0.4",
"@sanity/icons": "^2.11.2",
"@sanity/image-url": "^1.0.2",
"@sanity/preview-url-secret": "^1.6.5",
"@sanity/vision": "^3.35.0",
"@tailwindcss/typography": "^0.5.10",
"@types/node": "^20.11.30",
"@types/react": "^18.2.67",
"@types/react-dom": "^18.2.22",
"@sanity/assist": "3.0.3",
"@sanity/icons": "2.11.8",
"@sanity/image-url": "1.0.2",
"@sanity/preview-url-secret": "1.6.7",
"@sanity/vision": "3.37.2",
"@tailwindcss/typography": "^0.5.12",
"@types/node": "^20.12.7",
"@types/react": "^18.2.75",
"@types/react-dom": "^18.2.24",
"@vercel/speed-insights": "^1.0.10",
"autoprefixer": "^10.4.18",
"autoprefixer": "^10.4.19",
"date-fns": "^3.6.0",
"next": "latest",
"next-sanity": "^8.4.4",
"postcss": "^8.4.37",
"next-sanity": "9.0.0",
"postcss": "^8.4.38",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rxjs": "^7.8.1",
"sanity": "^3.35.0",
"sanity-plugin-asset-source-unsplash": "^2.0.1",
"sanity": "3.37.2",
"sanity-plugin-asset-source-unsplash": "3.0.0",
"server-only": "^0.0.1",
"styled-components": "^6.1.8",
"tailwindcss": "^3.4.1",
"typescript": "5.4.2"
"styled-components": "6.1.8",
"tailwindcss": "^3.4.3",
"typescript": "5.4.5"
},
"devDependencies": {
"@next/env": "latest",
......
{
"path": "'./{app,sanity}/**/*.{ts,tsx,js,jsx}'"
}
This diff is collapsed.
import { groq, type PortableTextBlock } from "next-sanity";
import type { Image } from "sanity";
import { groq } from "next-sanity";
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 {
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`
const postFields = /* groq */ `
_id,
"status": select(_originalId in path("drafts.**") => "draft", "published"),
"title": coalesce(title, "Untitled"),
......@@ -39,23 +17,12 @@ export const heroQuery = groq`*[_type == "post" && defined(slug.current)] | orde
content,
${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] {
${postFields}
}`;
export type MoreStoriesQueryResponse = Post[] | null;
export const postQuery = groq`*[_type == "post" && slug.current == $slug] [0] {
content,
${postFields}
}`;
export type PostQueryResponse =
| (Post & {
content?: PortableTextBlock[] | null;
})
| null;
This diff is collapsed.
{
"compilerOptions": {
"target": "es5",
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
// Use module: preserve, and remove moduleResolution, esModuleInterop and resolveJsonModule once Next ships support
"module": "esnext",
"moduleResolution": "node",
"moduleResolution": "bundler",
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true,
"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