Add task data layer and server actions
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
'use server';
|
||||
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { createTask, deleteTask, isStatus, moveTask } from '@/lib/tasks';
|
||||
|
||||
export async function addTask(formData: FormData) {
|
||||
const title = String(formData.get('title') ?? '').trim();
|
||||
if (!title) return;
|
||||
await createTask(title, String(formData.get('assignee') ?? ''));
|
||||
revalidatePath('/');
|
||||
}
|
||||
|
||||
export async function setStatus(formData: FormData) {
|
||||
const id = Number(formData.get('id'));
|
||||
const status = formData.get('status');
|
||||
if (!Number.isInteger(id) || !isStatus(status)) return;
|
||||
await moveTask(id, status);
|
||||
revalidatePath('/');
|
||||
}
|
||||
|
||||
export async function removeTask(formData: FormData) {
|
||||
const id = Number(formData.get('id'));
|
||||
if (!Number.isInteger(id)) return;
|
||||
await deleteTask(id);
|
||||
revalidatePath('/');
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { getPool } from './db';
|
||||
|
||||
export type Status = 'todo' | 'doing' | 'done';
|
||||
export const STATUSES: Status[] = ['todo', 'doing', 'done'];
|
||||
|
||||
export type Task = {
|
||||
id: number;
|
||||
title: string;
|
||||
status: Status;
|
||||
assignee: string | null;
|
||||
notes: string | null;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
};
|
||||
|
||||
export const isStatus = (v: unknown): v is Status => typeof v === 'string' && (STATUSES as string[]).includes(v);
|
||||
|
||||
export async function listTasks(): Promise<Task[]> {
|
||||
const { rows } = await getPool().query<Task>(
|
||||
'SELECT id, title, status, assignee, notes, created_at, updated_at FROM tasks ORDER BY id'
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export async function createTask(title: string, assignee?: string | null): Promise<Task> {
|
||||
const { rows } = await getPool().query<Task>(
|
||||
'INSERT INTO tasks (title, assignee) VALUES ($1, $2) RETURNING *',
|
||||
[title.trim().slice(0, 200), assignee?.trim().slice(0, 80) || null]
|
||||
);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
export async function moveTask(id: number, status: Status): Promise<Task | null> {
|
||||
const { rows } = await getPool().query<Task>(
|
||||
'UPDATE tasks SET status = $2, updated_at = now() WHERE id = $1 RETURNING *',
|
||||
[id, status]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function deleteTask(id: number): Promise<boolean> {
|
||||
const r = await getPool().query('DELETE FROM tasks WHERE id = $1', [id]);
|
||||
return (r.rowCount ?? 0) > 0;
|
||||
}
|
||||
Reference in New Issue
Block a user