Workers cloudflare làm việc với database D1 SQL Database
D1 SQL Database là giống như là SQLlite có nhiệm vụ lưu trữ , mình nghĩ nó sinh ra để phục vụ cho workers để thuận tiện cho code
Như thường lệ mình dùng wrangler với lệnh cài npm i wrangler
Đầu tiên mình khởi tạo dự án với wrang init
Các bạn chọn theo tùy chọn của mình ,mình thì chọn bộ khởi đầu javascript vì dễ debug là không phải đợi lâu so với ts
Đầu tiên mình tạo database với tên là tong :
wrangler d1 create tong
Ở đây mình tiếp tục xử lý ở file wrangler.jsonc
Cơ chế của cloudfare sẽ tự động đăng nhập mà không cần các bạn gọi ra
Mình tạo tables với lệnh :
wrangler d1 execute tong --remote --command "CREATE TABLE views (websiteid INTEGER NOT NULL,postid INTEGER NOT NULL,count INTEGER,created_at TEXT DEFAULT CURRENT_TIMESTAMP);"
Tiếp theo mình sẽ tạo index với lệnh :CREATE INDEX idx_website_post_id ON views(websiteid, postid);
Vậy là mình đã tạo xong D1 SQL giờ code tiếp là xong :
export default {
async fetch(request, env) {
const url = new URL(request.url);
const method = request.method;
if (method === "POST" && url.pathname === "/update-view") {
// 🟢 Nhận dữ liệu đầu vào
const { website_id, post_id, increment = 1 } = await request.json();
// 🔄 Kiểm tra xem bản ghi đã tồn tại chưa
const existing = await env.DB.prepare("SELECT count FROM views WHERE websiteid = ? AND postid = ?")
.bind(website_id, post_id)
.first();
if (existing) {
// 🟡 Nếu đã tồn tại, cập nhật count
const newCount = existing.count + increment;
await env.DB.prepare("UPDATE views SET count = ? WHERE websiteid = ? AND postid = ?")
.bind(newCount, website_id, post_id)
.run();
return new Response(JSON.stringify({ message: "Updated", count: newCount }), { status: 200 });
} else {
// 🟢 Nếu chưa tồn tại, tạo mới
await env.DB.prepare("INSERT INTO views (websiteid, postid, count) VALUES (?, ?, ?)")
.bind(website_id, post_id, increment)
.run();
return new Response(JSON.stringify({ message: "Created", count: increment }), { status: 201 });
}
}
if (method === "GET" && url.pathname.startsWith("/get-view/")) {
// 🔵 Lấy dữ liệu view
const [, , website_id, post_id] = url.pathname.split("/");
const result = await env.DB.prepare("SELECT count FROM views WHERE websiteid = ? AND postid = ?")
.bind(website_id, post_id)
.first();
return new Response(JSON.stringify(result || { message: "Not Found" }), { status: result ? 200 : 404 });
}
if (method === "DELETE" && url.pathname.startsWith("/delete-view/")) {
// 🔴 Xóa dữ liệu view
const [, , website_id, post_id] = url.pathname.split("/");
const { success } = await env.DB.prepare("DELETE FROM views WHERE websiteid = ? AND postid = ?")
.bind(website_id, post_id)
.run();
return new Response(JSON.stringify({ message: success ? "Deleted" : "Not Found" }), { status: success ? 200 : 404 });
}
return new Response("Not Found", { status: 404 });
}
};