Unverified Commit 394bbf62 authored by Espen Hovlandsdal's avatar Espen Hovlandsdal Committed by GitHub

Improve sanity.io example (#18227)

parent 5d586269
NEXT_PUBLIC_SANITY_PROJECT_ID=
NEXT_PUBLIC_SANITY_DATASET=
SANITY_API_TOKEN=
SANITY_PREVIEW_SECRET=
\ No newline at end of file
SANITY_PREVIEW_SECRET=
......@@ -70,6 +70,7 @@ cp .env.local.example .env.local
Then set each variable on `.env.local`:
- `NEXT_PUBLIC_SANITY_PROJECT_ID` should be the `projectId` value from the `sanity.json` file created in step 2.
- `NEXT_PUBLIC_SANITY_DATASET` should be the `dataset` value from the `sanity.json` file created in step 2 - defaults to `production` if not set.
- `SANITY_API_TOKEN` should be the API token generated in the previous step.
- `SANITY_PREVIEW_SECRET` can be any random string (but avoid spaces), like `MY_SECRET` - this is used for [Preview Mode](https://nextjs.org/docs/advanced-features/preview-mode).
......@@ -77,6 +78,7 @@ Your `.env.local` file should look like this:
```bash
NEXT_PUBLIC_SANITY_PROJECT_ID=...
NEXT_PUBLIC_SANITY_DATASET=...
SANITY_API_TOKEN=...
SANITY_PREVIEW_SECRET=...
```
......
import { urlForImage } from '../lib/sanity'
export default function Avatar({ name, picture }) {
return (
<div className="flex items-center">
<img src={picture} className="w-12 h-12 rounded-full mr-4" alt={name} />
<img
src={urlForImage(picture).height(96).width(96).fit('crop').url()}
className="w-12 h-12 rounded-full mr-4"
alt={name}
/>
<div className="text-xl font-bold">{name}</div>
</div>
)
......
import cn from 'classnames'
import Link from 'next/link'
import { imageBuilder } from '../lib/sanity'
import { urlForImage } from '../lib/sanity'
export default function CoverImage({ title, url, slug }) {
const image = (
export default function CoverImage({ title, slug, image: source }) {
const image = source ? (
<img
width={2000}
height={1000}
......@@ -11,8 +11,10 @@ export default function CoverImage({ title, url, slug }) {
className={cn('shadow-small', {
'hover:shadow-medium transition-shadow duration-200': slug,
})}
src={imageBuilder.image(url).height(1000).width(2000).url()}
src={urlForImage(source).height(1000).width(2000).url()}
/>
) : (
<div style={{ paddingTop: '50%', backgroundColor: '#ddd' }} />
)
return (
......
......@@ -14,7 +14,7 @@ export default function HeroPost({
return (
<section>
<div className="mb-8 md:mb-16">
<CoverImage slug={slug} title={title} url={coverImage} />
<CoverImage slug={slug} title={title} image={coverImage} />
</div>
<div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<div>
......
......@@ -36,7 +36,7 @@ export default function Meta() {
name="description"
content={`A statically generated blog example using Next.js and ${CMS_NAME}.`}
/>
<meta property="og:image" content={HOME_OG_IMAGE_URL} />
<meta property="og:image" content={HOME_OG_IMAGE_URL} key="ogImage" />
</Head>
)
}
......@@ -11,7 +11,7 @@ export default function PostHeader({ title, coverImage, date, author }) {
<Avatar name={author.name} picture={author.picture} />
</div>
<div className="mb-8 md:mb-16 sm:mx-0">
<CoverImage title={title} url={coverImage} />
<CoverImage title={title} image={coverImage} />
</div>
<div className="max-w-2xl mx-auto">
<div className="block md:hidden mb-6">
......
......@@ -14,7 +14,7 @@ export default function PostPreview({
return (
<div>
<div className="mb-5">
<CoverImage slug={slug} title={title} url={coverImage} />
<CoverImage slug={slug} title={title} image={coverImage} />
</div>
<h3 className="text-3xl mb-3 leading-snug">
<Link as={`/posts/${slug}`} href="/posts/[slug]">
......
import client, { previewClient } from './sanity'
const getUniquePosts = (posts) => {
const slugs = new Set()
return posts.filter((post) => {
if (slugs.has(post.slug)) {
return false
} else {
slugs.add(post.slug)
return true
}
})
}
const postFields = `
name,
title,
date,
excerpt,
'slug': slug.current,
'coverImage': coverImage.asset->url,
'author': author->{name, 'picture': picture.asset->url},
`
const getClient = (preview) => (preview ? previewClient : client)
export async function getPreviewPostBySlug(slug) {
const data = await getClient(true).fetch(
`*[_type == "post" && slug.current == $slug] | order(date desc){
${postFields}
content
}`,
{ slug }
)
return data[0]
}
export async function getAllPostsWithSlug() {
const data = await client.fetch(`*[_type == "post"]{ 'slug': slug.current }`)
return data
}
export async function getAllPostsForHome(preview) {
const results = await getClient(preview)
.fetch(`*[_type == "post"] | order(date desc, _updatedAt desc){
${postFields}
}`)
return getUniquePosts(results)
}
export async function getPostAndMorePosts(slug, preview) {
const curClient = getClient(preview)
const [post, morePosts] = await Promise.all([
curClient
.fetch(
`*[_type == "post" && slug.current == $slug] | order(_updatedAt desc) {
${postFields}
content,
}`,
{ slug }
)
.then((res) => res?.[0]),
curClient.fetch(
`*[_type == "post" && slug.current != $slug] | order(date desc, _updatedAt desc){
${postFields}
content,
}[0...2]`,
{ slug }
),
])
return { post, morePosts: getUniquePosts(morePosts) }
}
export const sanityConfig = {
// Find your project ID and dataset in `sanity.json` in your studio project
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || 'production',
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
useCdn: process.env.NODE_ENV === 'production',
// useCdn == true gives fast, cheap responses using a globally distributed cache.
// Set this to false if your application require the freshest possible
// data always (potentially slightly slower and a bit more expensive).
}
const postFields = `
_id,
name,
title,
date,
excerpt,
coverImage,
"slug": slug.current,
"author": author->{name, picture},
`
export const indexQuery = `
*[_type == "post"] | order(date desc, _updatedAt desc) {
${postFields}
}`
export const postQuery = `
{
"post": *[_type == "post" && slug.current == $slug] | order(_updatedAt desc) | [0] {
content,
${postFields}
},
"morePosts": *[_type == "post" && slug.current != $slug] | order(date desc, _updatedAt desc) | [0...2] {
content,
${postFields}
}
}`
export const postSlugsQuery = `
*[_type == "post" && defined(slug.current)][].slug.current
`
export const postBySlugQuery = `
*[_type == "post" && slug.current == $slug][0] {
${postFields}
}
`
import sanityClient from '@sanity/client'
import sanityImage from '@sanity/image-url'
import {
createImageUrlBuilder,
createPreviewSubscriptionHook,
} from 'next-sanity'
import { sanityConfig } from './config'
const options = {
// Find your project ID and dataset in `sanity.json` in your studio project
dataset: 'production',
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
useCdn: process.env.NODE_ENV === 'production',
// useCdn == true gives fast, cheap responses using a globally distributed cache.
// Set this to false if your application require the freshest possible
// data always (potentially slightly slower and a bit more expensive).
}
export const imageBuilder = createImageUrlBuilder(sanityConfig)
const client = sanityClient(options)
export const urlForImage = (source) =>
imageBuilder.image(source).auto('format').fit('max')
export const imageBuilder = sanityImage(client)
export const previewClient = sanityClient({
...options,
useCdn: false,
token: process.env.SANITY_API_TOKEN,
})
export default client
export const usePreviewSubscription = createPreviewSubscriptionHook(
sanityConfig
)
/**
* Server-side Sanity utilities. By having these in a separate file from the
* utilities we use on the client side, we are able to tree-shake (remove)
* code that is not used on the client side.
*/
import { createClient } from 'next-sanity'
import { sanityConfig } from './config'
export const sanityClient = createClient(sanityConfig)
export const previewClient = createClient({
...sanityConfig,
useCdn: false,
token: process.env.SANITY_API_TOKEN,
})
export const getClient = (preview) => (preview ? previewClient : sanityClient)
export function overlayDrafts(docs) {
const documents = docs || []
const overlayed = documents.reduce((map, doc) => {
if (!doc._id) {
throw new Error('Ensure that `_id` is included in query projection')
}
const isDraft = doc._id.startsWith('drafts.')
const id = isDraft ? doc._id.slice(7) : doc._id
return isDraft || !map.has(id) ? map.set(id, doc) : map
}, new Map())
return Array.from(overlayed.values())
}
......@@ -8,10 +8,9 @@
},
"dependencies": {
"@sanity/block-content-to-react": "2.0.7",
"@sanity/client": "1.149.2",
"@sanity/image-url": "0.140.17",
"classnames": "2.2.6",
"date-fns": "2.10.0",
"next-sanity": "0.1.5",
"next": "latest",
"react": "^16.13.0",
"react-dom": "^16.13.0"
......
import { getPreviewPostBySlug } from '../../lib/api'
import { postBySlugQuery } from '../../lib/queries'
import { previewClient } from '../../lib/sanity.server'
export default async function preview(req, res) {
// Check the secret and next parameters
......@@ -10,8 +11,10 @@ export default async function preview(req, res) {
return res.status(401).json({ message: 'Invalid token' })
}
// Fetch the headless CMS to check if the provided `slug` exists
const post = await getPreviewPostBySlug(req.query.slug)
// Check if the post with the given `slug` exists
const post = await previewClient.fetch(postBySlugQuery, {
slug: req.query.slug,
})
// If the slug doesn't exist prevent preview mode from being enabled
if (!post) {
......
import Head from 'next/head'
import Container from '../components/container'
import MoreStories from '../components/more-stories'
import HeroPost from '../components/hero-post'
import Intro from '../components/intro'
import Layout from '../components/layout'
import { getAllPostsForHome } from '../lib/api'
import Head from 'next/head'
import { CMS_NAME } from '../lib/constants'
import { indexQuery } from '../lib/queries'
import { getClient, overlayDrafts } from '../lib/sanity.server'
export default function Index({ allPosts, preview }) {
const heroPost = allPosts[0]
......@@ -36,7 +37,7 @@ export default function Index({ allPosts, preview }) {
}
export async function getStaticProps({ preview = false }) {
const allPosts = await getAllPostsForHome(preview)
const allPosts = overlayDrafts(await getClient(preview).fetch(indexQuery))
return {
props: { allPosts, preview },
}
......
import Head from 'next/head'
import { useRouter } from 'next/router'
import ErrorPage from 'next/error'
import Container from '../../components/container'
......@@ -7,16 +8,28 @@ import Header from '../../components/header'
import PostHeader from '../../components/post-header'
import SectionSeparator from '../../components/section-separator'
import Layout from '../../components/layout'
import { getAllPostsWithSlug, getPostAndMorePosts } from '../../lib/api'
import PostTitle from '../../components/post-title'
import Head from 'next/head'
import { CMS_NAME } from '../../lib/constants'
import { postQuery, postSlugsQuery } from '../../lib/queries'
import { urlForImage, usePreviewSubscription } from '../../lib/sanity'
import { sanityClient, getClient, overlayDrafts } from '../../lib/sanity.server'
export default function Post({ post, morePosts, preview }) {
export default function Post({ data = {}, preview }) {
const router = useRouter()
if (!router.isFallback && !post?.slug) {
const slug = data?.post?.slug
const {
data: { post, morePosts },
} = usePreviewSubscription(postQuery, {
params: { slug },
initialData: data,
enabled: preview && slug,
})
if (!router.isFallback && !slug) {
return <ErrorPage statusCode={404} />
}
return (
<Layout preview={preview}>
<Container>
......@@ -30,7 +43,17 @@ export default function Post({ post, morePosts, preview }) {
<title>
{post.title} | Next.js Blog Example with {CMS_NAME}
</title>
{/* <meta property="og:image" content={post.ogImage.url} /> */}
{post.coverImage && (
<meta
key="ogImage"
property="og:image"
content={urlForImage(post.coverImage)
.width(1200)
.height(627)
.fit('crop')
.url()}
/>
)}
</Head>
<PostHeader
title={post.title}
......@@ -50,25 +73,25 @@ export default function Post({ post, morePosts, preview }) {
}
export async function getStaticProps({ params, preview = false }) {
const data = await getPostAndMorePosts(params.slug, preview)
const { post, morePosts } = await getClient(preview).fetch(postQuery, {
slug: params.slug,
})
return {
props: {
preview,
post: data?.post || null,
morePosts: data?.morePosts || null,
data: {
post,
morePosts: overlayDrafts(morePosts),
},
},
}
}
export async function getStaticPaths() {
const allPosts = await getAllPostsWithSlug()
const paths = await sanityClient.fetch(postSlugsQuery)
return {
paths:
allPosts?.map((post) => ({
params: {
slug: post.slug,
},
})) || [],
paths: paths.map((slug) => ({ params: { slug } })),
fallback: true,
}
}
......@@ -12,24 +12,6 @@ export default createSchema({
// to the ones provided by any plugins that are installed
types: schemaTypes.concat([
/* Your types here! */
{
name: 'author',
type: 'document',
title: 'Author',
fields: [
{
name: 'name',
title: 'Name',
type: 'string',
},
{
name: 'picture',
title: 'Picture',
type: 'image',
},
],
},
{
name: 'post',
type: 'document',
......@@ -40,6 +22,14 @@ export default createSchema({
title: 'Title',
type: 'string',
},
{
name: 'slug',
title: 'Slug',
type: 'slug',
options: {
source: 'title',
},
},
{
name: 'content',
title: 'Content',
......@@ -67,13 +57,23 @@ export default createSchema({
type: 'reference',
to: [{ type: 'author' }],
},
],
},
{
name: 'author',
type: 'document',
title: 'Author',
fields: [
{
name: 'slug',
title: 'Slug',
type: 'slug',
options: {
source: 'title',
},
name: 'name',
title: 'Name',
type: 'string',
},
{
name: 'picture',
title: 'Picture',
type: 'image',
},
],
},
......
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