Viết lại cách số 1 ở trên (giờ viết 1 back-end trong luôn dự án)
Database
db\index.ts
import*as todos from'./tables/todos';exportdefault { todos }
db\tables\connection.ts
import mysql from"mysql2/promise";exportdefaultmysql.createPool({ host:'localhost', user:'root', password:'', database:'todo_app'});
db\tables\queryUtils.ts
import pool from './connection';
export async function SelectQuery<T>(queryString: string, params?: any) {
const [results] = await pool.execute(queryString, params);
return results as T[];
}
export async function ModifyQuery<T>(queryString: string, params?: any) {
const [results] = await pool.query(queryString, params);
return results as T[];
}
db\tables\todos.ts
import {SelectQuery,ModifyQuery} from './queryUtils';
export interface ITodosRow {
id: number; description: string; isCompleted: 0 | 1;
}
export function getAll() {
return SelectQuery<ITodosRow>('SELECT * FROM todos;');
}
export function getOne(id: number) {
return SelectQuery<ITodosRow>('SELECT * FROM todos WHERE id = ?;', [id]);
}
export function insert(todoItem: string) {
return ModifyQuery('INSERT INTO todos (description) VALUE (?);', [todoItem])
}
export function update(id: number, description: string, isCompleted: number) {
return ModifyQuery('UPDATE todos SET description=?,isCompleted=? WHERE id=?;', [description, isCompleted, id]);
}
export function drop(id: number) {
return ModifyQuery('DELETE FROM todos WHERE id=?;', [id]);
}
API
app\api\todos\route.ts
import { NextResponse } from 'next/server';
import db from '@/db';
export async function GET() {
const todos = await db.todos.getAll();
return NextResponse.json(todos);
}
export async function POST(request: Request) {
const { description }: Partial<Todo> = await request.json();
if (!description) return NextResponse.json({ "message": "Missing required data" })
const result: any = await db.todos.insert(description);
return NextResponse.json({ message: 'Todo created', id: result.insertId });
}
export async function PUT(request: Request) {
const { id, description, isCompleted }: Todo = await request.json()
if (!description) return NextResponse.json({ "message": "Missing required data" })
try {
const result = await db.todos.update(id, description, isCompleted);
return NextResponse.json({ message: 'Update created', id: result })
} catch (error) {
console.log(error)
return NextResponse.json({ message: 'Internal Server Error', error });
}
}
export async function DELETE(request: Request) {
const { id }: Partial<Todo> = await request.json();
if (!id) return NextResponse.json({ "message": "Todo id required" });
try {
const [todo] = await db.todos.drop(id);
return NextResponse.json(todo);
} catch (error) {
console.log(error);
return NextResponse.json({
message: 'Internal Server Error',
error
});
}
}
app\api\todos[id]\route.ts
import { NextRequest, NextResponse } from "next/server";
import db from '@/db';
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: number }> }) {
const id = (await params).id;
if (!id) return NextResponse.json({ "message": "Missing required data" })
const todo = await db.todos.getOne(id as number);
if(!todo.length) return NextResponse.json({ "message": "Missing required data" });
return NextResponse.json(todo[0]);
}