more sanity

This commit is contained in:
christian 2024-04-27 20:41:49 +02:00
parent 7ccd7e5b8c
commit dc8baf8d18
5 changed files with 59 additions and 33 deletions

View File

@ -1,7 +0,0 @@
<script>
export let data;
</script>
<h2>{data.post.title}</h2>
<p>data.</p>

33
src/lib/queries.js Normal file
View File

@ -0,0 +1,33 @@
/**
* Example of how you could re-use GROQ queries across different contexts with Javascript.
* As your schema evolves, this pattern will be useful to keep your data in sync across all surfaces.
*/
export function getPostsQuery(extraFilter) {
return /* groq */ `*[
_type == "post" &&
publishedAt < now()
${extraFilter ? `&& ${extraFilter}` : ''}
] | order(publishedAt desc) {
title,
slug,
coverImage,
_createdAt,
_updatedAt,
body,
}`
}
// Insert the return component calling `getContent()` below
/**
* You can also re-use parts of projections as fragments.
* In this case, we're defining that, to render an author card, we need their name, slug & image.
*/
export const POST_CARD_FRAGMENT = `
title,
slug,
coverImage,
_createdAt,
_updatedAt,
body,
`

View File

@ -0,0 +1,23 @@
import { client } from '$lib/sanity/client.js'
import { POST_CARD_FRAGMENT, getPostsQuery } from '$lib/queries.js'
// Fetch all valid posts & authors to display in the homepage
export async function load() {
const data = await client.fetch(/* groq */ `{
"posts": ${getPostsQuery()},
"post": *[_type == "post"] {
${POST_CARD_FRAGMENT}
}
}`)
if (data) {
return {
status: 200,
body: data
}
}
return {
status: 404
}
}

View File

@ -1,28 +1,5 @@
<script>
import { client } from '/src/utils/sanity/client.js'
export let data;
// Fetch content with GROQ
async function getContent() {
const CONTENT_QUERY = `*[_type == "project"] {
...,
coverImage {
...,
asset->
},
duration {
...
},
tags[],
body
}
`
const content = await client.fetch(CONTENT_QUERY)
return content
}
const posts = getContent();
// Log content to console
getContent().then(content => console.log(content))
// Insert the return component calling `getContent()` below
</script>
<p>{posts.title}</p>
<p>{data.posts}</p>