sveltekit api 요청

sting01·2023년 4월 13일

sveltekit

목록 보기
2/9

reqeustEvent

api 폴더 추가 필요
GET, POST, PATCH, DELETE

routes/api 폴더 안에서 REST API 관련 처리 가능.

helper 함수 {json}으로 적용
// return new Response(JSON.stringify(comments), {
// header: {
// 'Content-Type': 'application/json',
// },
// });

=> json(comments);

comments 폴더 내 +server.js

import { json } from '@sveltejs/kit';
import { comments } from '$lib/comments.js';

export const GET = () => {
	// return new Response(JSON.stringify(comments), {
	// 	header: {
	// 		'Content-Type': 'application/json',
	// 	},
	// });

	return json(comments);
};

export const POST = async ({ request }) => {
	// export async function POST(requestEvent) {
	// 	const { request } = requestEvent;
	const { text } = await request.json();
	const newComment = {
		id: comments.length + 1,
		text,
	};
	comments.push(newComment);

	// return new Response(JSON.stringify(newComment), { status: 201 });
	return json(newComment, { status: 201 });
};

comments - [commentId] 폴더 내 +server.js

prams를 가져와서 적용

import { json } from '@sveltejs/kit';
import { comments } from '$lib/comments.js';

export function GET(requestEvent) {
	const { params } = requestEvent;
	const { commentId } = params;

	const findComment = comments.find(
		comment => comment.id === parseInt(commentId),
	);

	return json(findComment);
}

export const PATCH = async ({ params, request }) => {
	const { commentId } = params;
	const { text } = await request.json();

	const findComment = comments.find(
		comment => comment.id === parseInt(commentId),
	);

	findComment.text = text;

	return json(findComment);
};

export const DELETE = async ({ params, request }) => {
	const { commentId } = params;
	const deleteComment = comments.find(
		comment => comment.id === parseInt(commentId),
	);
	const index = comments.findIndex(
		comment => comment.id === parseInt(commentId),
	);

	comments.splice(index, 1);

	return json(deleteComment);
};

1개의 댓글

comment-user-thumbnail
2024년 11월 6일

I thought it was simple at first, but Cookie Clicker 2 has so much depth!

답글 달기