Skip to content

Commit

Permalink
Merge pull request #64 from Blazity/client-queries
Browse files Browse the repository at this point in the history
Client queries
  • Loading branch information
Pierniki authored Oct 13, 2023
2 parents 55644a2 + dc03ee8 commit 69936b9
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 43 deletions.
4 changes: 1 addition & 3 deletions src/app/[lang]/article/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,7 @@ export default async function Web({ params: { slug, lang } }: ArticlePageProps)
</section>
)}
</article>
{article.recommendedArticles.length > 0 && (
<RecommendedArticles recommendedArticles={article.recommendedArticles} lang={lang} />
)}
<RecommendedArticles id={article.id} lang={lang} />
</>
)
}
28 changes: 24 additions & 4 deletions src/app/api/webhook/handleRevalidation.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { revalidateTag } from "next/cache"
import { revalidatePath, revalidateTag } from "next/cache"
import { z } from "zod"
import { hygraphLocaleToStandardNotation } from "@/i18n/i18n"
import { Tag } from "@/lib/tags"
import { NextRequestWithValidBody } from "./validateBody"

export function handleRevalidation<T extends RevalidationBody>(req: NextRequestWithValidBody<T>) {
const tags = modelTypeToTags[req.validBody.data.__typename]
const article = req.validBody.data
if (isArticle(article)) {
article.localizations.forEach(({ locale, slug }) => {
revalidatePath(`/${hygraphLocaleToStandardNotation(locale)}/article/${slug}`, "page")
})
}
tags.forEach(revalidateTag)
return req
}
Expand All @@ -17,15 +24,28 @@ const modelTypeToTags: Record<RevalidationBody["data"]["__typename"], Tag[]> = {
Homepage: ["HOMEPAGE"],
Category: ["CATEGORY"],
Author: ["ARTICLE"],
Quiz: ["ARTICLE"],
}

export const modelTypesSchema = z.object({
__typename: z.enum(["Article", "Navigation", "Footer", "Page", "Homepage", "Category", "Author", "Quiz"]),
__typename: z.enum(["Article", "Navigation", "Footer", "Page", "Homepage", "Category", "Author"]),
})

const isArticle = (data: RevalidationBody["data"]): data is z.infer<typeof articleSchema> =>
data.__typename === "Article"

const articleSchema = z.object({
__typename: z.enum(["Article"]),
localizations: z.array(
z.object({
locale: z.string(),
slug: z.string(),
})
),
id: z.string(),
})

const bodySchema = z.object({
data: modelTypesSchema,
data: articleSchema.or(modelTypesSchema),
})

type RevalidationBody = z.infer<typeof bodySchema>
2 changes: 1 addition & 1 deletion src/components/CodeSnippet/CodeSnippet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ function CodeSnippet({ content }: CodeSnippetProps) {
return (
<CodeBlock
language={"javascript"}
customStyle={{ "border-radius": "15px" }}
customStyle={{ borderRadius: "15px" }}
text={String(content)}
showLineNumbers={true}
theme={nord}
Expand Down
49 changes: 33 additions & 16 deletions src/components/RecommendedArticles/RecommendedArticles.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,43 @@
import { Locale } from "@/i18n/i18n"
import { ArticlesGrid } from "../ArticlesGrid/ArticlesGrid"
"use client"

type imageInfo = {
description?: { text: string } | null
data: { url: string }
}
import { useQuery } from "@tanstack/react-query"
import { Locale } from "@/i18n/i18n"
import { getArticleRecommendedArticles } from "@/lib/client"
import { ArticleCard, hygraphArticleToCardProps } from "../ArticleCard/ArticleCard"

export type RecommendedArticle = {
tags: string[]
title: string
slug: string
id: string
image?: imageInfo | null
}
type RecommendedArticlesProps = { id: string; lang: Locale }

type RecommendedArticlesProps = { recommendedArticles: RecommendedArticle[]; lang: Locale }
export function RecommendedArticles({ id, lang }: RecommendedArticlesProps) {
const { data: recommendedArticles, isLoading } = useQuery({
queryKey: [`recommended-articles`, id],
queryFn: () => getArticleRecommendedArticles({ locale: lang, id }),
})

export async function RecommendedArticles({ recommendedArticles, lang }: RecommendedArticlesProps) {
if (!isLoading && recommendedArticles?.length === 0) return null
return (
<section className="w-full py-4">
<h2 className="mb-8 text-2xl font-bold">Related articles</h2>
<ArticlesGrid locale={lang} articles={recommendedArticles} />
<div className={`grid grid-cols-3 gap-8`}>
{isLoading &&
Array.from(Array(3).keys()).map((idx) => {
return <ArticleSkeleton key={`skeleton-${idx}`} />
})}
{!isLoading &&
recommendedArticles?.map((article) => {
return (
<ArticleCard
key={`trending-${article.id}`}
article={hygraphArticleToCardProps(article)}
tagsPosition="under"
locale={lang}
/>
)
})}
</div>
</section>
)
}

function ArticleSkeleton() {
return <div className=" h-[481px] animate-pulse rounded-xl bg-gray-100"></div>
}
11 changes: 10 additions & 1 deletion src/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Locale, standardNotationToHygraphLocale } from "@/i18n/i18n"
import {
getArticleBySlugQuery,
getArticleMetadataBySlugQuery,
getArticleRecommendedArticlesQuery,
getArticlesQuantityQuery,
getRecentArticlesQuery,
listArticlesByCategoryQuery,
Expand Down Expand Up @@ -155,11 +156,19 @@ export async function getRecentArticles(variables: { locale: Locale; skip?: numb
return { articles, count: articlesConnection.aggregate.count }
}

export async function getArticleRecommendedArticles(variables: { locale: Locale; id: string }) {
const { article } = await graphqlFetch({
cache: "force-cache",
document: getArticleRecommendedArticlesQuery,
variables,
})
return article ? article.recommendedArticles : []
}

export async function getArticleBySlug(variables: { locale: Locale; slug: string }) {
const { articles } = await graphqlFetch({
cache: "force-cache",
document: getArticleBySlugQuery,
tags: ["ARTICLE"],
variables,
})
return articles[0] ?? null
Expand Down
44 changes: 26 additions & 18 deletions src/lib/queries/articles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,31 @@ export const getRecentArticlesQuery = graphql(`
}
`)

export const getArticleRecommendedArticlesQuery = graphql(`
query getArticleRecommendedArticles($locales: [Locale!]!, $id: ID!) {
article(locales: $locales, where: { id: $id }) {
recommendedArticles {
title
slug
id
tags
publishedAt
author {
name
}
image {
description {
text
}
data {
url
}
}
}
}
}
`)

export const getArticleBySlugQuery = graphql(`
query getArticleBySlug($locales: [Locale!]!, $slug: String!) {
articles(locales: $locales, where: { slug: $slug }) {
Expand Down Expand Up @@ -96,24 +121,7 @@ export const getArticleBySlugQuery = graphql(`
}
}
}
recommendedArticles {
title
slug
id
tags
publishedAt
author {
name
}
image {
description {
text
}
data {
url
}
}
}
categories {
title
slug
Expand Down

0 comments on commit 69936b9

Please sign in to comment.