Skip to content

Commit

Permalink
fix redis post req
Browse files Browse the repository at this point in the history
  • Loading branch information
dromzeh committed Oct 31, 2023
1 parent 9e1c74f commit 72be496
Showing 1 changed file with 11 additions and 16 deletions.
27 changes: 11 additions & 16 deletions app/api/incr.ts → app/api/incr/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<NextResponse> {
if (req.method !== "POST") {
return new NextResponse("use POST", { status: 405 });
}
export async function POST(req: NextRequest): Promise<NextResponse> {
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),
Expand All @@ -33,15 +27,16 @@ export default async function incr(req: NextRequest): Promise<NextResponse> {
.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 });
}

0 comments on commit 72be496

Please sign in to comment.