[nextjs]SNS Server-1(API CRUD,myapp11)

๐Ÿ‘‰๐Ÿป SNS Server๋ฅผ ๋งŒ๋“ค์–ด ๋ด…๋‹ˆ๋‹ค.
Let’s build an SNS server.

๐Ÿ‘‰๐Ÿป ์›น์‚ฌ์ดํŠธ ํ™”๋ฉด ์ด์ „์— CRUD API๋ถ€๋ถ„์„ ๋จผ์ € ๊ตฌํ˜„ํ•ด ๋ด…๋‹ˆ๋‹ค.
We will implement the CRUD API first, before working on the website interface.

๐Ÿ“ ์ „์ฒด ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ / Project Structure

myapp11/ (Root Directory)
โ”œโ”€โ”€ ๐Ÿ“ app/                    # Next.js App Router
โ”‚   โ”œโ”€โ”€ ๐Ÿ“ api/                
โ”‚   โ”‚   โ””โ”€โ”€ ๐Ÿ“ posts/          
โ”‚   โ”‚       โ””โ”€โ”€ ๐Ÿ“„ route.ts    # CRUD API
โ”‚   โ”œโ”€โ”€ ๐Ÿ“„ layout.tsx          
โ”‚   โ”œโ”€โ”€ ๐Ÿ“„ page.tsx            # Main Home
โ”‚   โ””โ”€โ”€ ๐Ÿ“„ globals.css        
โ”œโ”€โ”€ ๐Ÿ“ lib/                    
โ”‚   โ””โ”€โ”€ ๐Ÿ“„ db.ts               # SQLite dbconnection(data.sqlite)
โ”œโ”€โ”€ ๐Ÿ“„ data.sqlite             # Local SQLite Database
โ””โ”€โ”€ ๐Ÿ“„ Caddyfile               # Caddy file

๐Ÿ“ Nextjs ํ”„๋กœ์ ํŠธ ์‹œ์ž‘ / Starting a Next.js project(myapp11)

npx create-next-app@latest

๐Ÿ“ SQLite์„ค์น˜ / Installing SQLite

cd ~/myapp11
npm install better-sqlite3
npm install -D @types/better-sqlite3

๐Ÿ“ API์ฝ”๋“œ ์ž‘์„ฑ
Writing API code

โœ”๏ธ myapp11/app/api/posts/route.ts

// ~/myapp11/app/api/posts/route.ts
import db from '@/lib/db';
import { randomUUID } from 'crypto';

export async function GET() {
  // R - ์ฝ๊ธฐ / Read
  const posts = db.prepare('SELECT * FROM posts ORDER BY created_at DESC').all();
  return Response.json(posts);
}

export async function POST(req: Request) {
  // C - ์ƒ์„ฑ / Create
  const { content } = await req.json();
  if (!content) return Response.json({ error: '๋‚ด์šฉ ์—†์Œ / Content is required' }, { status: 400 });

  const id = randomUUID();
  db.prepare('INSERT INTO posts (id, content) VALUES (?, ?)').run(id, content);

  const post = db.prepare('SELECT * FROM posts WHERE id = ?').get(id);
  return Response.json(post);
}

export async function PUT(req: Request) {
  // U - ์ˆ˜์ • / Update
  const { id, content } = await req.json();
  if (!id || !content) {
    return Response.json({ error: 'id์™€ content ํ•„์š” / id and content are required' }, { status: 400 });
  }

  const result = db.prepare('UPDATE posts SET content = ? WHERE id = ?').run(content, id);
  
  if (result.changes === 0) {
    return Response.json({ error: 'ํ•ด๋‹น ๊ธ€ ์—†์Œ / Post not found' }, { status: 404 });
  }

  const post = db.prepare('SELECT * FROM posts WHERE id = ?').get(id);
  return Response.json(post);
}

export async function DELETE(req: Request) {
  // D - ์‚ญ์ œ / Delete
  const { searchParams } = new URL(req.url);
  const id = searchParams.get('id');
  if (!id) return Response.json({ error: 'id ํ•„์š” / You need id' }, { status: 400 });

  db.prepare('DELETE FROM posts WHERE id = ?').run(id);
  return Response.json({ ok: true });
}

โœ”๏ธ myapp11/db/db.ts

// ~/myapp11/lib/db.ts
import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';

const dir = path.join(process.cwd());
const dbPath = path.join(dir, 'data.sqlite');

const db = new Database(dbPath);

// ํ…Œ์ด๋ธ” ์ƒ์„ฑ / Create table if it doesn't exist
db.exec(`
  CREATE TABLE IF NOT EXISTS posts (
    id TEXT PRIMARY KEY,
    content TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );
`);

export default db;

๐Ÿ“ Nextjs ์„œ๋ฒ„์‹คํ–‰ / Running the Next.js server

npm run dev

๐Ÿ“ ๋‹ค๋ฅธ ํ„ฐ๋ฏธ๋„์—์„œ ๊ธ€์ €์žฅ ๋ฐ ๋ชฉ๋ก ๋ณด๊ธฐ
Save posts and view lists from another terminal

โœ”๏ธ ํ„ฐ๋ฏธ๋„์—์„œ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค.()
Run it in the terminal.

# ๊ธ€ ์“ฐ๊ธฐ / Write a Post

curl -X POST http://localhost:3000/api/posts -H "Content-Type: application/json" -d '{"content":"์ฒซ ๊ธ€! sqlite์— ์ €์žฅ๋จ"}'

# ๊ธ€ ๋ชฉ๋ก ๋ณด๊ธฐ / View list of posts
curl http://localhost:3000/api/posts

# ๊ธ€ ์ˆ˜์ •ํ•˜๊ธฐ / Edit Post
curl -X PUT http://localhost:3000/api/posts -H "Content-Type: application/json" -d '{"id":"a1b2c3d4-...","content":"์ˆ˜์ •๋œ ๋‚ด์šฉ/Revised content!"}'


# ๊ธ€ ์‚ญ์ œ / Delete post
curl -X DELETE "http://localhost:3000/api/posts?id=a1b2c3d4-..."

1)๊ธ€์“ฐ๊ธฐ๋ฅผ ๋ธŒ๋ผ์šฐ์ €์—์„œ ํ•˜๋ ค๋ฉด page.tsx์— ๊ธ€ ์ „์†กํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ๋ณ„๋„๋กœ ๋งŒ๋“ค์–ด์•ผํ•ฉ๋‹ˆ๋‹ค.
To write posts directly in the browser, you need to create separate code in page.tsx to submit the content.

โœ”๏ธ ๋ธŒ๋ผ์šฐ์ €์—์„œ ๊ธ€ ๋ชฉ๋ก ๋ณด๊ธฐ
View the list of posts in the browser

API

์š”ํ•œ๋ณต์Œ 8์žฅ 32์ ˆ / John 8:32

“๊ทธ๋ฆฌ๊ณ  ๋„ˆํฌ๋Š” ์ง„๋ฆฌ๋ฅผ ์•Œ๊ฒŒ ๋  ๊ฒƒ์ด๋ฉฐ, ์ง„๋ฆฌ๊ฐ€ ๋„ˆํฌ๋ฅผ ์ž์œ ๋กญ๊ฒŒ ํ•  ๊ฒƒ์ด๋‹ค.”

“Then you will know the truth ,and the truth will set you free”

Leave a Reply