- Created .gitignore to exclude build outputs, logs, and environment files. - Added nuxt.config.ts for project configuration, enabling Tailwind CSS and Pinia modules. - Initialized package.json with scripts for development and production, and added necessary dependencies. - Generated pnpm-lock.yaml for dependency management. - Created README.md with setup instructions and development guidelines. - Implemented server API examples in server/api/ directory, demonstrating various use cases. - Added middleware for logging requests and responses. - Included example Vue components and pages for server API interaction. - Established basic project structure for Nuxt 4 application development.
58 lines
1.8 KiB
TypeScript
58 lines
1.8 KiB
TypeScript
/**
|
|
* 케이스 5: 단일 파일에서 HTTP 메서드 분기
|
|
*
|
|
* - 파일명에 메서드 접미사 없음 → 모든 HTTP 메서드 수신
|
|
* - getMethod(event): 현재 요청의 HTTP 메서드 반환
|
|
* - URL:
|
|
* GET /api/05-items/1 → 아이템 조회
|
|
* PUT /api/05-items/1 → 아이템 수정
|
|
* DELETE /api/05-items/1 → 아이템 삭제
|
|
*
|
|
* 팁: 메서드별로 파일을 분리하는 것이 더 명확하지만,
|
|
* 관련 로직을 한 파일에 모을 때 이 패턴을 사용합니다.
|
|
*/
|
|
|
|
interface Item {
|
|
id: string;
|
|
title: string;
|
|
done: boolean;
|
|
}
|
|
|
|
// 인메모리 저장소 (실제 프로젝트에서는 DB 사용)
|
|
const items: Map<string, Item> = new Map([
|
|
["1", { id: "1", title: "Nuxt 서버 공부하기", done: false }],
|
|
["2", { id: "2", title: "Pinia 연습하기", done: true }],
|
|
]);
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const id = getRouterParam(event, "id") ?? "";
|
|
const method = event.method; // 'GET' | 'POST' | 'PUT' | 'DELETE' ...
|
|
|
|
if (method === "GET") {
|
|
const item = items.get(id);
|
|
if (!item) throw createError({ statusCode: 404, statusMessage: "아이템 없음" });
|
|
return item;
|
|
}
|
|
|
|
if (method === "PUT") {
|
|
const body = await readBody<Partial<Item>>(event);
|
|
const item = items.get(id);
|
|
if (!item) throw createError({ statusCode: 404, statusMessage: "아이템 없음" });
|
|
|
|
const updated: Item = { ...item, ...body, id };
|
|
items.set(id, updated);
|
|
return updated;
|
|
}
|
|
|
|
if (method === "DELETE") {
|
|
const existed = items.delete(id);
|
|
if (!existed) throw createError({ statusCode: 404, statusMessage: "아이템 없음" });
|
|
|
|
setResponseStatus(event, 204);
|
|
return null;
|
|
}
|
|
|
|
// 허용하지 않는 메서드
|
|
throw createError({ statusCode: 405, statusMessage: "허용되지 않는 메서드" });
|
|
});
|