import { blob } from "https://esm.town/v/std/blob";
const BLOB_PREFIX = "items_";
export default async function server(request: Request): Promise<Response> {
const url = new URL(request.url);
const path = url.pathname;
const method = request.method;
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
if (method === "OPTIONS") {
return new Response(null, { headers });
}
if (path === "/") {
return new Response(getInstructions(), {
headers: { ...headers, "Content-Type": "text/plain" },
});
}
if (path === "/items") {
if (method === "GET") {
const items = await getAllItems();
return jsonResponse(items, headers);
} else if (method === "POST") {
const item = await request.json();
const id = await createItem(item);
return jsonResponse({ id }, headers, 201);
}
} else if (path.startsWith("/items/")) {
const id = path.split("/")[2];
if (method === "GET") {
const item = await getItem(id);
return item ? jsonResponse(item, headers) : notFoundResponse(headers);
} else if (method === "PUT") {
const item = await request.json();
await updateItem(id, item);
return new Response(null, { headers, status: 204 });
} else if (method === "DELETE") {
await deleteItem(id);
return new Response(null, { headers, status: 204 });
}
}
return new Response("Not Found", { headers, status: 404 });
}
async function getAllItems() {
const keys = await blob.list(BLOB_PREFIX);
const items = await Promise.all(
keys.map(async (key) => ({
id: key.key.slice(BLOB_PREFIX.length),
...await blob.getJSON(key.key),
}))
);
return items;
}
async function getItem(id: string) {
return await blob.getJSON(`${BLOB_PREFIX}${id}`);
}
async function createItem(item: any) {
const id = crypto.randomUUID();
await blob.setJSON(`${BLOB_PREFIX}${id}`, item);
return id;
}
async function updateItem(id: string, item: any) {
await blob.setJSON(`${BLOB_PREFIX}${id}`, item);
}
async function deleteItem(id: string) {
await blob.delete(`${BLOB_PREFIX}${id}`);
}
function jsonResponse(data: any, headers: HeadersInit, status = 200) {
return new Response(JSON.stringify(data), {
headers: { ...headers, "Content-Type": "application/json" },
status,
});
}
function notFoundResponse(headers: HeadersInit) {
return new Response("Not Found", { headers, status: 404 });
}
function getInstructions() {