From 72be496e29f7dd8963b816472c4ce7a6e7191775 Mon Sep 17 00:00:00 2001 From: Marcel <65048232+dromzeh@users.noreply.github.com> Date: Tue, 31 Oct 2023 20:28:46 +0000 Subject: [PATCH] fix redis post req --- app/api/{incr.ts => incr/route.ts} | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) rename app/api/{incr.ts => incr/route.ts} (62%) diff --git a/app/api/incr.ts b/app/api/incr/route.ts similarity index 62% rename from app/api/incr.ts rename to app/api/incr/route.ts index 8aa2ca9..6a21e76 100644 --- a/app/api/incr.ts +++ b/app/api/incr/route.ts @@ -2,29 +2,23 @@ import { Redis } from "@upstash/redis"; import { NextRequest, NextResponse } from "next/server"; const redis = Redis.fromEnv(); -export const config = { - runtime: "edge", -}; +export const runtime = "edge"; -export default async function incr(req: NextRequest): Promise { - if (req.method !== "POST") { - return new NextResponse("use POST", { status: 405 }); - } +export async function POST(req: NextRequest): Promise { if (req.headers.get("Content-Type") !== "application/json") { - return new NextResponse("must be json", { status: 400 }); + return new NextResponse("content type must be json", { status: 400 }); } const body = await req.json(); let slug: string | undefined = undefined; - if ("slug" in body) { - slug = body.slug; - } - if (!slug) { - return new NextResponse("Slug not found", { status: 400 }); - } + + if ("slug" in body) slug = body.slug; + + if (!slug) return new NextResponse("slug not found", { status: 400 }); + const ip = req.ip; + if (ip) { - // Hash the IP in order to not store it directly in your db. const buf = await crypto.subtle.digest( "SHA-256", new TextEncoder().encode(ip), @@ -33,15 +27,16 @@ export default async function incr(req: NextRequest): Promise { .map((b) => b.toString(16).padStart(2, "0")) .join(""); - // deduplicate the ip for each slug const isNew = await redis.set(["deduplicate", hash, slug].join(":"), true, { nx: true, ex: 24 * 60 * 60, }); + if (!isNew) { new NextResponse(null, { status: 202 }); } } + await redis.incr(["pageviews", "projects", slug].join(":")); return new NextResponse(null, { status: 202 }); } \ No newline at end of file