Skip to content

Instantly share code, notes, and snippets.

@mxkaske
Created June 15, 2023 18:26
Show Gist options
  • Save mxkaske/813d83d0850d77a0c596c1004bf5b887 to your computer and use it in GitHub Desktop.
Save mxkaske/813d83d0850d77a0c596c1004bf5b887 to your computer and use it in GitHub Desktop.
Create a reduced REST API with Upstash and Nextjs App Router and optional catch-all segments
// /app/api/upstash/[[...slug]].ts
import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
type Params = { slug: string | string[] | undefined };
function createKey(slug: Params["slug"]) {
return slug ? [...(Array.isArray(slug) ? slug : [slug])].join(":") : "_root";
}
export async function GET(_: Request, { params }: { params: Params }) {
const key = createKey(params.slug);
const state = await redis.json.get(key);
return new Response(JSON.stringify(state), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
export async function POST(request: Request, { params }: { params: Params }) {
const json = await request.json();
const key = createKey(params.slug);
await redis.json.set(key, "$", JSON.stringify(json));
return new Response("Created", { status: 201 });
}
export async function PUT(request: Request, { params }: { params: Params }) {
const { name, value } = await request.json();
const key = createKey(params.slug);
try {
await redis.json.set(key, `$.${name}`, JSON.stringify(value));
} catch {
// UpstashError: ERR new objects must be created at the root
await redis.json.set(key, "$", { [name]: JSON.stringify(value) });
}
return new Response("Updated", { status: 201 });
}
export async function DELETE(request: Request, { params }: { params: Params }) {
const key = createKey(params.slug);
await redis.del(key);
return new Response("Deleted", { status: 200 });
}
@mxkaske
Copy link
Author

mxkaske commented Jun 15, 2023

How to call it:

export async function createState() {
  return await fetch("/api/v1/upstash/state", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      title: "Hello World",
      status: "Ready",
    }),
  });
};

export async function getState() {
  return await fetch("/api/v1/upstash/state");
};

export async function updateState() {
  return await fetch("/api/v1/upstash/state", {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      name: "title",
      value: "New World",
    }),
  });
};

export async function deleteState() {
  return await fetch("/api/v1/upstash/state", {
    method: "DELETE",
  });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment