HTTP 伺服器:使用 SQLite3 執行 CRUD 操作
在 Github 上編輯
使用 oak 中介軟體框架和 SQLite3 資料庫,用於 CRUD 路由的 HTTP 伺服器範例。它示範了使用 HTTP 方法 (Get、Post、Put、Delete、Options) 對基於檔案的 SQLite 資料庫執行 CRUD (建立、讀取、更新和刪除) 操作
import { Application, Router } from "jsr:@oak/oak";
import { Database } from "jsr:@db/sqlite";
從記憶體資料庫或檔案開啟資料庫。這裡使用記憶體資料庫來示範 CRUD。
const peopleDb = new Database(":memory:");
peopleDb.exec(
"CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT not null,age INTEGER not null)",
);
const app = new Application();
const router = new Router();
router
.post("/people", async (ctx) => {
const { name, age } = await ctx.request.body.json();
peopleDb.exec("INSERT INTO people (name, age) VALUES (?,?)", name, age);
const lastInsertRowId = peopleDb.lastInsertRowId; // Get the last inserted row ID
ctx.response.status = 201;
ctx.response.body = { id: lastInsertRowId, name, age };
});
router.get("/people", (ctx) => {
const users = peopleDb.prepare("SELECT * FROM people").all();
ctx.response.body = users;
});
router.put("/people/:id", async (ctx) => {
const { name, age } = await ctx.request.body.json();
peopleDb.prepare("UPDATE people SET name =?, age=? WHERE id = ?").run(
name,
age,
ctx.params.id,
);
ctx.response.body = { message: "person updated successfully as requested" };
});
router.delete("/people/:id", (ctx) => {
peopleDb.prepare("DELETE FROM people WHERE id = ?").run(ctx.params.id);
ctx.response.body = "person removed successfully as requested";
});
app.use(router.routes());
app.use(router.allowedMethods());
const PORT = 8369; // Any available port number can be defined here
console.log(`Server is running on https://127.0.0.1:${PORT}`);
await app.listen({ port: PORT });
使用 Deno CLI 在本機執行此範例
deno run -A https://deno-docs.dev.org.tw/examples/scripts/http_server_oak_crud_middleware_with_sqlite3_db.ts