File size: 1,887 Bytes
e430ef5
 
 
 
 
03d1608
 
e430ef5
03d1608
e430ef5
 
 
473c03c
e430ef5
 
 
 
 
 
03d1608
e430ef5
 
 
 
 
 
 
a97ae75
e430ef5
 
 
 
a97ae75
e430ef5
a97ae75
 
e430ef5
 
 
 
 
 
 
4514534
e430ef5
 
 
 
 
 
 
 
 
 
4514534
e430ef5
 
4514534
e430ef5
 
 
03d1608
 
e430ef5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// server.js
import { serve } from "bun";
import { createClient } from "redis";
import fs from "fs";
import path from "path";

const redis = createClient();
await redis.connect();

const handler = async (req) => {
  const url = new URL(req.url);
  const { pathname, searchParams } = url;

  // serve index.html
  if (pathname === "/" && req.method === "GET") {
    return new Response(await Bun.file("./index.html").text(), {
      headers: { "Content-Type": "text/html" },
    });
  }

  // save key/value
  if (pathname === "/save" && req.method === "POST") {
    const { key, value } = await req.json();
    if (!key || !value) return new Response("Missing key or value", { status: 400 });
    await redis.set(key, value);
    return new Response("Saved");
  }

  // get value by key
  if (pathname === "/get" && req.method === "GET") {
    const key = searchParams.get("key");
    if (!key) return new Response("Missing key", { status: 400 });
    const value = await redis.get(key);
    return new Response(value ?? "Key not found");
  }

  // delete key
  if (pathname === "/delete" && req.method === "POST") {
    const key = searchParams.get("key");
    if (!key) return new Response("Missing key", { status: 400 });
    const deleted = await redis.del(key);
    return new Response(deleted ? "Deleted" : "Key not found");
  }

  // list all
  if (pathname === "/all" && req.method === "GET") {
    const keys = await redis.keys("*");
    const data = await Promise.all(
      keys.map(async (k) => ({ key: k, value: await redis.get(k) }))
    );
    return new Response(JSON.stringify(data), {
      headers: { "Content-Type": "application/json" },
    });
  }

  return new Response("Not found", { status: 404 });
};

serve({
  fetch: handler,
  port: process.env.PORT ? Number(process.env.PORT) : 7860,
});

console.log("Bun server running on port", process.env.PORT || 7860);