feat: lab05 done
- add Users/Create User feature - add Pages Functions - add d1 database
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* @typedef {import('@cloudflare/workers-types').D1Database} D1Database
|
||||
*/
|
||||
|
||||
export async function onRequestGet(context) {
|
||||
const DB = context.env.DB;
|
||||
|
||||
// return all users
|
||||
const stmt = await DB.prepare("SELECT * FROM users");
|
||||
const users = (await stmt.run()).results;
|
||||
|
||||
return new Response(JSON.stringify(users), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function onRequestPost(context) {
|
||||
/**
|
||||
* @type {D1Database}
|
||||
*/
|
||||
const DB = context.env.DB;
|
||||
const { name } = await context.request.json();
|
||||
|
||||
// create a new user
|
||||
const stmt = DB.prepare("INSERT INTO users (name) VALUES (?)").bind(name);
|
||||
|
||||
try {
|
||||
const result = await stmt.run();
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error("Failed to create user");
|
||||
}
|
||||
|
||||
const userId = result.meta.last_row_id;
|
||||
const stmt2 = await DB.prepare("SELECT * FROM users WHERE id = ?").bind(userId);
|
||||
const userResult = await stmt2.run();
|
||||
const user = userResult.results[0];
|
||||
|
||||
return new Response(JSON.stringify(user), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
status: 201,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error creating user:", error);
|
||||
return new Response("Error creating user", { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user