base_ui/server/api/users/index.ts

37 lines
1.0 KiB
TypeScript
Raw Permalink Normal View History

2025-02-01 09:34:55 +00:00
import { defineEventHandler, getQuery, readBody } from 'h3';
// In-memory "database" for demonstration
const users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
];
export default defineEventHandler(async (event) => {
const method = event.node.req.method;
if (method === 'GET') {
// Get all users
const query = getQuery(event);
const search = query.search?.toString();
if (search) {
return users.filter((user) =>
user.name.toLowerCase().includes(search.toLowerCase())
);
}
return users;
}
if (method === 'POST') {
// Create a new user
const body = await readBody(event);
if (!body.name || !body.email) {
throw createError({ statusCode: 400, statusMessage: 'Name and email are required' });
}
const newUser = { id: users.length + 1, ...body };
users.push(newUser);
return { message: 'User created', user: newUser };
}
throw createError({ statusCode: 405, statusMessage: 'Method not allowed' });
});