rsnext/examples/cms-strapi/lib/api.js
Luis Alvarez D 2cd691050a
Add new import flow to CMS examples (#14053)
[ch2502]

- Added new import flow to every CMS example, using the deploy button, and removed `vercel.json`
- Replaced `dotenv` with the new env support in outdated examples
2020-06-11 23:44:23 +00:00

140 lines
2.3 KiB
JavaScript

async function fetchAPI(query, { variables } = {}) {
const res = await fetch(`${process.env.NEXT_PUBLIC_STRAPI_API_URL}/graphql`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
}
return json.data
}
export async function getPreviewPostBySlug(slug) {
const data = await fetchAPI(
`
query PostBySlug($where: JSON) {
posts(where: $where) {
slug
}
}
`,
{
variables: {
where: {
slug,
},
},
}
)
return data?.posts[0]
}
export async function getAllPostsWithSlug() {
const data = fetchAPI(`
{
posts {
slug
}
}
`)
return data?.allPosts
}
export async function getAllPostsForHome(preview) {
const data = await fetchAPI(
`
query Posts($where: JSON){
posts(sort: "date:desc", limit: 10, where: $where) {
title
slug
excerpt
date
coverImage {
url
}
author {
name
picture {
url
}
}
}
}
`,
{
variables: {
where: {
...(preview ? {} : { status: 'published' }),
},
},
}
)
return data?.posts
}
export async function getPostAndMorePosts(slug, preview) {
const data = await fetchAPI(
`
query PostBySlug($where: JSON, $where_ne: JSON) {
posts(where: $where) {
title
slug
content
date
ogImage: coverImage{
url
}
coverImage {
url
}
author {
name
picture {
url
}
}
}
morePosts: posts(sort: "date:desc", limit: 2, where: $where_ne) {
title
slug
excerpt
date
coverImage {
url
}
author {
name
picture {
url
}
}
}
}
`,
{
preview,
variables: {
where: {
slug,
...(preview ? {} : { status: 'published' }),
},
where_ne: {
...(preview ? {} : { status: 'published' }),
slug_ne: slug,
},
},
}
)
return data
}