Skip to content

Commit

Permalink
fix: views by using fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
mxkaske committed May 14, 2023
1 parent 270bed4 commit 0868af6
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 13 deletions.
3 changes: 2 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=
UPSTASH_REDIS_REST_TOKEN=
# NEXT_PUBLIC_VERCEL_URL=https://craft.mxkaske.dev
17 changes: 16 additions & 1 deletion app/api/incr/route.tsx → app/api/views/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,21 @@ const redis = Redis.fromEnv();
export const runtime = "edge";

export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const hasSlug = searchParams.has("slug");
const slug = hasSlug ? searchParams.get("slug") : undefined;

const views =
(await redis.get<number>(["pageviews", "posts", slug].join(":"))) ?? 0;

return new NextResponse(views.toString(), { status: 200 });
}

export async function POST(request: NextRequest) {
const ip = request.ip;
const searchParams = request.nextUrl.searchParams;
const hasSlug = searchParams.has("slug");
const slug = hasSlug ? searchParams.get("slug") : null;
const slug = hasSlug ? searchParams.get("slug") : undefined;

if (ip) {
const buf = await crypto.subtle.digest(
Expand All @@ -31,6 +42,10 @@ export async function GET(request: NextRequest) {
}
}

if (!slug) {
new NextResponse("Slug Not Found", { status: 404 });
}

await redis.incr(["pageviews", "posts", slug].join(":"));
return new NextResponse("Increased Counter", { status: 202 });
}
2 changes: 1 addition & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const calSans = LocalFont({
export const metadata: Metadata = {
title: "craft.mxkaske.dev",
description: "Never stop crafting.",
metadataBase: new URL("https://craft.mxkaske.dev"),
twitter: {
images: [`/api/og`],
card: "summary_large_image",
Expand All @@ -25,7 +26,6 @@ export const metadata: Metadata = {
images: [`/api/og`],
title: "craft.mxkaske.dev",
description: "Never stop crafting.",
url: "http://craft.mxkaske.dev", // FIXME: make it non-static
},
};

Expand Down
2 changes: 1 addition & 1 deletion app/post/[slug]/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function Content({ post }: { post: Post }) {
const MDXContent = useMDXComponent(post.body.code);

React.useEffect(() => {
fetch(`/api/incr?slug=${post.slug}`);
fetch(`/api/views?slug=${post.slug}`, { method: "POST" });
}, [post.slug]);

return (
Expand Down
6 changes: 1 addition & 5 deletions app/post/[slug]/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import React from "react";
import { allPosts } from "@/.contentlayer/generated";

export async function generateStaticParams() {
return allPosts.map((c) => ({ slug: c.url }));
}

export function generateMetadata({ params }: { params: { slug: string } }) {
const post = allPosts.find((c) => c.url === `/post/${params.slug}`);
return {
Expand All @@ -21,7 +17,7 @@ export function generateMetadata({ params }: { params: { slug: string } }) {
images: [`/api/og?title=${post?.title}&description=${post?.description}`],
title: post?.title,
description: post?.description,
url: `http://craft.mxkaske.dev/posts/${post?.slug}`,
url: `/posts/${post?.slug}`,
// Could alsop include `publishTime` and `author` - see https://nextjs.org/docs/app/api-reference/functions/generate-metadata#opengraph
},
};
Expand Down
12 changes: 8 additions & 4 deletions app/post/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { notFound } from "next/navigation";
import { Content } from "./content";
import { Github } from "lucide-react";
import { Link } from "@/components/mdx/link";
import { Redis } from "@upstash/redis";

const redis = Redis.fromEnv();
const URL =
process.env.VERCEL_ENV === "production"
? `https://craft.mxkaske/dev`
: process.env.NEXT_PUBLIC_VERCEL_URL;

function formatDate(date: Date) {
return new Intl.DateTimeFormat("en-US", {
Expand All @@ -28,8 +30,10 @@ export default async function CraftPage({
notFound();
}

const views =
(await redis.get<number>(["pageviews", "posts", post.slug].join(":"))) ?? 0;
const res = await fetch(`${URL}/api/views?slug=${post.slug}`, {
next: { revalidate: 10 },
});
const views = Number(await res.json());

return (
<article className="max-w-prose mx-auto">
Expand Down

0 comments on commit 0868af6

Please sign in to comment.