commit ff3f6e619bcb76ec7c86b2b92646405d5b7846a2 Author: Kar Date: Fri Sep 15 19:58:26 2023 +0530 init diff --git a/server.js b/server.js new file mode 100644 index 0000000..2443e9a --- /dev/null +++ b/server.js @@ -0,0 +1,71 @@ +// Dependencies +import { serve, write } from "bun"; +// Import users json file +import users from "./users.json"; +// Create server +serve({ + async fetch(request) { + // Get url and method + const { url, method } = request; + // Get pathname from url + const { pathname } = new URL(url); + // Get All Users + if (pathname === "/api/users" && method === "GET") { + return new Response(JSON.stringify(users), { + status: 200, + headers: { + "Content-Type": "application/json", + "Access-control-allow-origin": "*", + }, + }); + } + // Create User + if (pathname === "/api/users" && method === "POST") { + const body = await request.json(); + const newJson = users.concat(body); + write("./users.json", JSON.stringify(newJson), null, 2); + return new Response(JSON.stringify(newJson), { + status: 200, + headers: { + "Content-Type": "application/json", + "Access-control-allow-origin": "*", + }, + }); + } + // Delete User + // method == 0 is a DELETE request + if (pathname === "/api/users" && method == 0) { + const body = await request.json(); + const newJson = users.filter((user) => user.id !== body.id); + write("./users.json", JSON.stringify(newJson), null, 2); + return new Response(JSON.stringify(newJson), { + status: 200, + headers: { + "Content-Type": "application/json", + "Access-control-allow-origin": "*", + }, + }); + } + // Update User + if (pathname === "/api/users" && method === "PUT") { + const body = await request.json(); + const newJson = users.map((user) => { + if (user.id === body.id) { + return body; + } + return user; + }); + write("./users.json", JSON.stringify(newJson), null, 2); + return new Response(JSON.stringify(newJson), { + status: 200, + headers: { + "Content-Type": "application/json", + "Access-control-allow-origin": "*", + }, + }); + } + // Send 404 + return new Response("", { status: 404 }); + }, +}); +console.log("Server running on port 3000"); diff --git a/users.json b/users.json new file mode 100644 index 0000000..bca25bc --- /dev/null +++ b/users.json @@ -0,0 +1,8 @@ +[ + { "id": "1", "name": "John", "age": "25", "city": "New York" }, + { "id": "2", "name": "Steve", "age": "30", "city": "London" }, + { "id": "3", "name": "Bill", "age": "35", "city": "Paris" }, + { "id": "4", "name": "Ram", "age": "40", "city": "Jakarta" }, + { "id": "5", "name": "Rons", "age": "45", "city": "Tokyo" }, + { "id": "6", "name": "Luca", "age": "18", "city": "Argentina" } +]