Merge pull request 'feat: implement REST API backend with full CRUD and sync (#37)' (#44) from issue-37-api-rest into issue-35-web-setup
This commit is contained in:
commit
46ead345b4
18 changed files with 941 additions and 3 deletions
4
web/package-lock.json
generated
4
web/package-lock.json
generated
|
|
@ -15,7 +15,8 @@
|
|||
"next": "16.2.2",
|
||||
"pg": "^8.20.0",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4"
|
||||
"react-dom": "19.2.4",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
|
|
@ -8497,7 +8498,6 @@
|
|||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
|
||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@
|
|||
"next": "16.2.2",
|
||||
"pg": "^8.20.0",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4"
|
||||
"react-dom": "19.2.4",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
|
|
|
|||
52
web/src/app/api/lists/[id]/route.ts
Normal file
52
web/src/app/api/lists/[id]/route.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slLists } from '@/db/schema';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { updateListSchema } from '@/lib/validators';
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id } = await params;
|
||||
const body = await parseBody(request, (d) => updateListSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
const [updated] = await db
|
||||
.update(slLists)
|
||||
.set({ ...body.data, updatedAt: new Date() })
|
||||
.where(and(eq(slLists.id, id), eq(slLists.userId, auth.userId)))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(updated);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const [deleted] = await db
|
||||
.update(slLists)
|
||||
.set({ deletedAt: new Date(), updatedAt: new Date() })
|
||||
.where(and(eq(slLists.id, id), eq(slLists.userId, auth.userId)))
|
||||
.returning();
|
||||
|
||||
if (!deleted) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
85
web/src/app/api/lists/[id]/tasks/route.ts
Normal file
85
web/src/app/api/lists/[id]/tasks/route.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTasks, slLists, slTaskTags } from '@/db/schema';
|
||||
import { eq, and, isNull, asc, desc, inArray, SQL } from 'drizzle-orm';
|
||||
import { requireAuth } from '@/lib/api';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id: listId } = await params;
|
||||
|
||||
// Verify list belongs to user
|
||||
const [list] = await db
|
||||
.select({ id: slLists.id })
|
||||
.from(slLists)
|
||||
.where(and(eq(slLists.id, listId), eq(slLists.userId, auth.userId)));
|
||||
|
||||
if (!list) {
|
||||
return NextResponse.json({ error: 'List not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const url = request.nextUrl;
|
||||
const completed = url.searchParams.get('completed');
|
||||
const priority = url.searchParams.get('priority');
|
||||
const dueDate = url.searchParams.get('dueDate');
|
||||
const tags = url.searchParams.get('tags');
|
||||
const sortBy = url.searchParams.get('sortBy') || 'position';
|
||||
const sortOrder = url.searchParams.get('sortOrder') || 'asc';
|
||||
|
||||
const conditions: SQL[] = [
|
||||
eq(slTasks.listId, listId),
|
||||
eq(slTasks.userId, auth.userId),
|
||||
isNull(slTasks.deletedAt),
|
||||
isNull(slTasks.parentId),
|
||||
];
|
||||
|
||||
if (completed !== null) {
|
||||
conditions.push(eq(slTasks.completed, completed === 'true'));
|
||||
}
|
||||
if (priority !== null) {
|
||||
conditions.push(eq(slTasks.priority, parseInt(priority, 10)));
|
||||
}
|
||||
|
||||
// Build query
|
||||
let query = db
|
||||
.select()
|
||||
.from(slTasks)
|
||||
.where(and(...conditions));
|
||||
|
||||
// Sort
|
||||
const sortColumn = sortBy === 'priority' ? slTasks.priority
|
||||
: sortBy === 'dueDate' ? slTasks.dueDate
|
||||
: sortBy === 'createdAt' ? slTasks.createdAt
|
||||
: sortBy === 'title' ? slTasks.title
|
||||
: slTasks.position;
|
||||
|
||||
const orderFn = sortOrder === 'desc' ? desc : asc;
|
||||
const tasks = await query.orderBy(orderFn(sortColumn));
|
||||
|
||||
// Filter by tags if specified (post-query since it's a join table)
|
||||
if (tags) {
|
||||
const tagIds = tags.split(',');
|
||||
const taskTagRows = await db
|
||||
.select({ taskId: slTaskTags.taskId })
|
||||
.from(slTaskTags)
|
||||
.where(inArray(slTaskTags.tagId, tagIds));
|
||||
|
||||
const taskIdsWithTags = new Set(taskTagRows.map((r) => r.taskId));
|
||||
return NextResponse.json(tasks.filter((t) => taskIdsWithTags.has(t.id)));
|
||||
}
|
||||
|
||||
// Filter by dueDate if specified (before/on that date)
|
||||
if (dueDate) {
|
||||
const cutoff = new Date(dueDate);
|
||||
return NextResponse.json(
|
||||
tasks.filter((t) => t.dueDate && t.dueDate <= cutoff)
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(tasks);
|
||||
}
|
||||
36
web/src/app/api/lists/reorder/route.ts
Normal file
36
web/src/app/api/lists/reorder/route.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slLists } from '@/db/schema';
|
||||
import { eq, and, inArray } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { reorderSchema } from '@/lib/validators';
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const body = await parseBody(request, (d) => reorderSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
// Verify all lists belong to user
|
||||
const existing = await db
|
||||
.select({ id: slLists.id })
|
||||
.from(slLists)
|
||||
.where(and(eq(slLists.userId, auth.userId), inArray(slLists.id, body.data.ids)));
|
||||
|
||||
if (existing.length !== body.data.ids.length) {
|
||||
return NextResponse.json({ error: 'Some lists not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Update positions in order
|
||||
await Promise.all(
|
||||
body.data.ids.map((id, index) =>
|
||||
db
|
||||
.update(slLists)
|
||||
.set({ position: index, updatedAt: new Date() })
|
||||
.where(and(eq(slLists.id, id), eq(slLists.userId, auth.userId)))
|
||||
)
|
||||
);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
34
web/src/app/api/lists/route.ts
Normal file
34
web/src/app/api/lists/route.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slLists } from '@/db/schema';
|
||||
import { eq, isNull, and, asc } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { createListSchema } from '@/lib/validators';
|
||||
|
||||
export async function GET() {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const lists = await db
|
||||
.select()
|
||||
.from(slLists)
|
||||
.where(and(eq(slLists.userId, auth.userId), isNull(slLists.deletedAt)))
|
||||
.orderBy(asc(slLists.position));
|
||||
|
||||
return NextResponse.json(lists);
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const body = await parseBody(request, (d) => createListSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
const [list] = await db
|
||||
.insert(slLists)
|
||||
.values({ ...body.data, userId: auth.userId })
|
||||
.returning();
|
||||
|
||||
return NextResponse.json(list, { status: 201 });
|
||||
}
|
||||
228
web/src/app/api/sync/route.ts
Normal file
228
web/src/app/api/sync/route.ts
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slLists, slTasks, slTags, slTaskTags } from '@/db/schema';
|
||||
import { eq, and, gte } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { syncPushSchema, type SyncOperation } from '@/lib/validators';
|
||||
|
||||
// Idempotency key store (TTL 24h)
|
||||
const idempotencyStore = new Map<string, { result: unknown; expiresAt: number }>();
|
||||
|
||||
// Cleanup expired keys periodically
|
||||
function cleanupIdempotencyKeys() {
|
||||
const now = Date.now();
|
||||
for (const [key, entry] of idempotencyStore) {
|
||||
if (entry.expiresAt < now) {
|
||||
idempotencyStore.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const TTL_24H = 24 * 60 * 60 * 1000;
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const since = request.nextUrl.searchParams.get('since');
|
||||
if (!since) {
|
||||
return NextResponse.json({ error: 'Missing "since" parameter' }, { status: 400 });
|
||||
}
|
||||
|
||||
const sinceDate = new Date(since);
|
||||
if (isNaN(sinceDate.getTime())) {
|
||||
return NextResponse.json({ error: 'Invalid "since" timestamp' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Fetch all entities updated since timestamp (including soft-deleted)
|
||||
const [lists, tasks, tags] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(slLists)
|
||||
.where(and(eq(slLists.userId, auth.userId), gte(slLists.updatedAt, sinceDate))),
|
||||
db
|
||||
.select()
|
||||
.from(slTasks)
|
||||
.where(and(eq(slTasks.userId, auth.userId), gte(slTasks.updatedAt, sinceDate))),
|
||||
db
|
||||
.select()
|
||||
.from(slTags)
|
||||
.where(and(eq(slTags.userId, auth.userId), gte(slTags.createdAt, sinceDate))),
|
||||
]);
|
||||
|
||||
// Get task-tag relations for the affected tasks
|
||||
const taskIds = tasks.map((t) => t.id);
|
||||
let taskTags: { taskId: string; tagId: string }[] = [];
|
||||
if (taskIds.length > 0) {
|
||||
const { inArray } = await import('drizzle-orm');
|
||||
taskTags = await db
|
||||
.select()
|
||||
.from(slTaskTags)
|
||||
.where(inArray(slTaskTags.taskId, taskIds));
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
lists,
|
||||
tasks,
|
||||
tags,
|
||||
taskTags,
|
||||
syncedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const body = await parseBody(request, (d) => syncPushSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
cleanupIdempotencyKeys();
|
||||
|
||||
const results: { idempotencyKey: string; status: 'applied' | 'skipped'; error?: string }[] = [];
|
||||
|
||||
for (const op of body.data.operations) {
|
||||
const storeKey = `${auth.userId}:${op.idempotencyKey}`;
|
||||
|
||||
// Check idempotency
|
||||
const existing = idempotencyStore.get(storeKey);
|
||||
if (existing && existing.expiresAt > Date.now()) {
|
||||
results.push({ idempotencyKey: op.idempotencyKey, status: 'skipped' });
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await processOperation(op, auth.userId);
|
||||
idempotencyStore.set(storeKey, {
|
||||
result: true,
|
||||
expiresAt: Date.now() + TTL_24H,
|
||||
});
|
||||
results.push({ idempotencyKey: op.idempotencyKey, status: 'applied' });
|
||||
} catch (e) {
|
||||
results.push({
|
||||
idempotencyKey: op.idempotencyKey,
|
||||
status: 'skipped',
|
||||
error: e instanceof Error ? e.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ results, syncedAt: new Date().toISOString() });
|
||||
}
|
||||
|
||||
async function processOperation(op: SyncOperation, userId: string) {
|
||||
const { entityType, entityId, action, data } = op;
|
||||
const now = new Date();
|
||||
|
||||
switch (entityType) {
|
||||
case 'list': {
|
||||
if (action === 'create') {
|
||||
await db.insert(slLists).values({
|
||||
id: entityId,
|
||||
userId,
|
||||
name: (data as Record<string, unknown>)?.name as string || 'Untitled',
|
||||
color: (data as Record<string, unknown>)?.color as string | undefined,
|
||||
icon: (data as Record<string, unknown>)?.icon as string | undefined,
|
||||
position: (data as Record<string, unknown>)?.position as number | undefined,
|
||||
isInbox: (data as Record<string, unknown>)?.isInbox as boolean | undefined,
|
||||
}).onConflictDoNothing();
|
||||
} else if (action === 'update') {
|
||||
await verifyOwnership(slLists, entityId, userId);
|
||||
await db.update(slLists)
|
||||
.set({ ...(data as Record<string, unknown>), updatedAt: now })
|
||||
.where(and(eq(slLists.id, entityId), eq(slLists.userId, userId)));
|
||||
} else if (action === 'delete') {
|
||||
await verifyOwnership(slLists, entityId, userId);
|
||||
await db.update(slLists)
|
||||
.set({ deletedAt: now, updatedAt: now })
|
||||
.where(and(eq(slLists.id, entityId), eq(slLists.userId, userId)));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'task': {
|
||||
if (action === 'create') {
|
||||
const d = (data as Record<string, unknown>) || {};
|
||||
await db.insert(slTasks).values({
|
||||
id: entityId,
|
||||
userId,
|
||||
title: d.title as string || 'Untitled',
|
||||
listId: d.listId as string,
|
||||
notes: d.notes as string | undefined,
|
||||
priority: d.priority as number | undefined,
|
||||
dueDate: d.dueDate ? new Date(d.dueDate as string) : undefined,
|
||||
parentId: d.parentId as string | undefined,
|
||||
recurrence: d.recurrence as string | undefined,
|
||||
position: d.position as number | undefined,
|
||||
}).onConflictDoNothing();
|
||||
} else if (action === 'update') {
|
||||
await verifyOwnership(slTasks, entityId, userId);
|
||||
const raw = { ...(data as Record<string, unknown>), updatedAt: now } as Record<string, unknown>;
|
||||
if (raw.dueDate !== undefined) {
|
||||
raw.dueDate = raw.dueDate ? new Date(raw.dueDate as string) : null;
|
||||
}
|
||||
await db.update(slTasks)
|
||||
.set(raw)
|
||||
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
|
||||
} else if (action === 'delete') {
|
||||
await verifyOwnership(slTasks, entityId, userId);
|
||||
await db.update(slTasks)
|
||||
.set({ deletedAt: now, updatedAt: now })
|
||||
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'tag': {
|
||||
if (action === 'create') {
|
||||
const d = (data as Record<string, unknown>) || {};
|
||||
await db.insert(slTags).values({
|
||||
id: entityId,
|
||||
userId,
|
||||
name: d.name as string || 'Untitled',
|
||||
color: d.color as string | undefined,
|
||||
}).onConflictDoNothing();
|
||||
} else if (action === 'update') {
|
||||
await verifyTagOwnership(entityId, userId);
|
||||
await db.update(slTags)
|
||||
.set(data as Record<string, unknown>)
|
||||
.where(and(eq(slTags.id, entityId), eq(slTags.userId, userId)));
|
||||
} else if (action === 'delete') {
|
||||
await verifyTagOwnership(entityId, userId);
|
||||
await db.update(slTags)
|
||||
.set({ deletedAt: now })
|
||||
.where(and(eq(slTags.id, entityId), eq(slTags.userId, userId)));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'taskTag': {
|
||||
// entityId is used as taskId, tagId comes from data
|
||||
const d = (data as Record<string, unknown>) || {};
|
||||
const tagId = d.tagId as string;
|
||||
if (action === 'create') {
|
||||
await db.insert(slTaskTags)
|
||||
.values({ taskId: entityId, tagId })
|
||||
.onConflictDoNothing();
|
||||
} else if (action === 'delete') {
|
||||
await db.delete(slTaskTags)
|
||||
.where(and(eq(slTaskTags.taskId, entityId), eq(slTaskTags.tagId, tagId)));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async function verifyOwnership(table: any, entityId: string, userId: string) {
|
||||
const [row] = await db
|
||||
.select({ id: table.id })
|
||||
.from(table)
|
||||
.where(and(eq(table.id, entityId), eq(table.userId, userId)));
|
||||
if (!row) throw new Error('Entity not found or access denied');
|
||||
}
|
||||
|
||||
async function verifyTagOwnership(entityId: string, userId: string) {
|
||||
const [row] = await db
|
||||
.select({ id: slTags.id })
|
||||
.from(slTags)
|
||||
.where(and(eq(slTags.id, entityId), eq(slTags.userId, userId)));
|
||||
if (!row) throw new Error('Tag not found or access denied');
|
||||
}
|
||||
52
web/src/app/api/tags/[id]/route.ts
Normal file
52
web/src/app/api/tags/[id]/route.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTags } from '@/db/schema';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { updateTagSchema } from '@/lib/validators';
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id } = await params;
|
||||
const body = await parseBody(request, (d) => updateTagSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
const [updated] = await db
|
||||
.update(slTags)
|
||||
.set(body.data)
|
||||
.where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId)))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(updated);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const [deleted] = await db
|
||||
.update(slTags)
|
||||
.set({ deletedAt: new Date() })
|
||||
.where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId)))
|
||||
.returning();
|
||||
|
||||
if (!deleted) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
34
web/src/app/api/tags/route.ts
Normal file
34
web/src/app/api/tags/route.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTags } from '@/db/schema';
|
||||
import { eq, isNull, and, asc } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { createTagSchema } from '@/lib/validators';
|
||||
|
||||
export async function GET() {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const tags = await db
|
||||
.select()
|
||||
.from(slTags)
|
||||
.where(and(eq(slTags.userId, auth.userId), isNull(slTags.deletedAt)))
|
||||
.orderBy(asc(slTags.name));
|
||||
|
||||
return NextResponse.json(tags);
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const body = await parseBody(request, (d) => createTagSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
const [tag] = await db
|
||||
.insert(slTags)
|
||||
.values({ ...body.data, userId: auth.userId })
|
||||
.returning();
|
||||
|
||||
return NextResponse.json(tag, { status: 201 });
|
||||
}
|
||||
67
web/src/app/api/tasks/[id]/route.ts
Normal file
67
web/src/app/api/tasks/[id]/route.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTasks } from '@/db/schema';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { updateTaskSchema } from '@/lib/validators';
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id } = await params;
|
||||
const body = await parseBody(request, (d) => updateTaskSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
const updateData: Record<string, unknown> = {
|
||||
...body.data,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
// Convert dueDate string to Date
|
||||
if (body.data.dueDate !== undefined) {
|
||||
updateData.dueDate = body.data.dueDate ? new Date(body.data.dueDate) : null;
|
||||
}
|
||||
|
||||
// Set completedAt when toggling completed
|
||||
if (body.data.completed !== undefined) {
|
||||
updateData.completedAt = body.data.completed ? new Date() : null;
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(slTasks)
|
||||
.set(updateData)
|
||||
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(updated);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const [deleted] = await db
|
||||
.update(slTasks)
|
||||
.set({ deletedAt: new Date(), updatedAt: new Date() })
|
||||
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)))
|
||||
.returning();
|
||||
|
||||
if (!deleted) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
39
web/src/app/api/tasks/[id]/subtasks/route.ts
Normal file
39
web/src/app/api/tasks/[id]/subtasks/route.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTasks } from '@/db/schema';
|
||||
import { eq, and, isNull, asc } from 'drizzle-orm';
|
||||
import { requireAuth } from '@/lib/api';
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
// Verify parent task belongs to user
|
||||
const [parent] = await db
|
||||
.select({ id: slTasks.id })
|
||||
.from(slTasks)
|
||||
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)));
|
||||
|
||||
if (!parent) {
|
||||
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const subtasks = await db
|
||||
.select()
|
||||
.from(slTasks)
|
||||
.where(
|
||||
and(
|
||||
eq(slTasks.parentId, id),
|
||||
eq(slTasks.userId, auth.userId),
|
||||
isNull(slTasks.deletedAt)
|
||||
)
|
||||
)
|
||||
.orderBy(asc(slTasks.position));
|
||||
|
||||
return NextResponse.json(subtasks);
|
||||
}
|
||||
31
web/src/app/api/tasks/[id]/tags/[tagId]/route.ts
Normal file
31
web/src/app/api/tasks/[id]/tags/[tagId]/route.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTasks, slTaskTags } from '@/db/schema';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { requireAuth } from '@/lib/api';
|
||||
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string; tagId: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id: taskId, tagId } = await params;
|
||||
|
||||
// Verify task belongs to user
|
||||
const [task] = await db
|
||||
.select({ id: slTasks.id })
|
||||
.from(slTasks)
|
||||
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId)));
|
||||
|
||||
if (!task) {
|
||||
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(slTaskTags)
|
||||
.where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId)));
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
47
web/src/app/api/tasks/[id]/tags/route.ts
Normal file
47
web/src/app/api/tasks/[id]/tags/route.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTasks, slTags, slTaskTags } from '@/db/schema';
|
||||
import { eq, and, inArray } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { assignTagsSchema } from '@/lib/validators';
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const { id: taskId } = await params;
|
||||
|
||||
const body = await parseBody(request, (d) => assignTagsSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
// Verify task belongs to user
|
||||
const [task] = await db
|
||||
.select({ id: slTasks.id })
|
||||
.from(slTasks)
|
||||
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId)));
|
||||
|
||||
if (!task) {
|
||||
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Verify all tags belong to user
|
||||
const existingTags = await db
|
||||
.select({ id: slTags.id })
|
||||
.from(slTags)
|
||||
.where(and(eq(slTags.userId, auth.userId), inArray(slTags.id, body.data.tagIds)));
|
||||
|
||||
if (existingTags.length !== body.data.tagIds.length) {
|
||||
return NextResponse.json({ error: 'Some tags not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Insert (ignore conflicts)
|
||||
await db
|
||||
.insert(slTaskTags)
|
||||
.values(body.data.tagIds.map((tagId) => ({ taskId, tagId })))
|
||||
.onConflictDoNothing();
|
||||
|
||||
return NextResponse.json({ ok: true }, { status: 201 });
|
||||
}
|
||||
35
web/src/app/api/tasks/reorder/route.ts
Normal file
35
web/src/app/api/tasks/reorder/route.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTasks } from '@/db/schema';
|
||||
import { eq, and, inArray } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { reorderSchema } from '@/lib/validators';
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const body = await parseBody(request, (d) => reorderSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
// Verify all tasks belong to user
|
||||
const existing = await db
|
||||
.select({ id: slTasks.id })
|
||||
.from(slTasks)
|
||||
.where(and(eq(slTasks.userId, auth.userId), inArray(slTasks.id, body.data.ids)));
|
||||
|
||||
if (existing.length !== body.data.ids.length) {
|
||||
return NextResponse.json({ error: 'Some tasks not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
body.data.ids.map((id, index) =>
|
||||
db
|
||||
.update(slTasks)
|
||||
.set({ position: index, updatedAt: new Date() })
|
||||
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)))
|
||||
)
|
||||
);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
47
web/src/app/api/tasks/route.ts
Normal file
47
web/src/app/api/tasks/route.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/db/client';
|
||||
import { slTasks, slLists } from '@/db/schema';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { requireAuth, parseBody } from '@/lib/api';
|
||||
import { createTaskSchema } from '@/lib/validators';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
const body = await parseBody(request, (d) => createTaskSchema.parse(d));
|
||||
if (body.error) return body.error;
|
||||
|
||||
// Verify list belongs to user
|
||||
const [list] = await db
|
||||
.select({ id: slLists.id })
|
||||
.from(slLists)
|
||||
.where(and(eq(slLists.id, body.data.listId), eq(slLists.userId, auth.userId)));
|
||||
|
||||
if (!list) {
|
||||
return NextResponse.json({ error: 'List not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// If parentId, verify parent task belongs to user
|
||||
if (body.data.parentId) {
|
||||
const [parent] = await db
|
||||
.select({ id: slTasks.id })
|
||||
.from(slTasks)
|
||||
.where(and(eq(slTasks.id, body.data.parentId), eq(slTasks.userId, auth.userId)));
|
||||
|
||||
if (!parent) {
|
||||
return NextResponse.json({ error: 'Parent task not found' }, { status: 404 });
|
||||
}
|
||||
}
|
||||
|
||||
const [task] = await db
|
||||
.insert(slTasks)
|
||||
.values({
|
||||
...body.data,
|
||||
dueDate: body.data.dueDate ? new Date(body.data.dueDate) : undefined,
|
||||
userId: auth.userId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return NextResponse.json(task, { status: 201 });
|
||||
}
|
||||
46
web/src/app/api/ws-ticket/route.ts
Normal file
46
web/src/app/api/ws-ticket/route.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { requireAuth } from '@/lib/api';
|
||||
|
||||
// In-memory ticket store (TTL 30s, single use)
|
||||
const ticketStore = new Map<string, { userId: string; expiresAt: number }>();
|
||||
|
||||
const TTL_30S = 30 * 1000;
|
||||
|
||||
// Cleanup expired tickets
|
||||
function cleanupTickets() {
|
||||
const now = Date.now();
|
||||
for (const [key, entry] of ticketStore) {
|
||||
if (entry.expiresAt < now) {
|
||||
ticketStore.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and consume a WS ticket. Returns userId if valid, null otherwise.
|
||||
*/
|
||||
export function consumeTicket(ticket: string): string | null {
|
||||
const entry = ticketStore.get(ticket);
|
||||
if (!entry || entry.expiresAt < Date.now()) {
|
||||
ticketStore.delete(ticket);
|
||||
return null;
|
||||
}
|
||||
ticketStore.delete(ticket); // Single use
|
||||
return entry.userId;
|
||||
}
|
||||
|
||||
export async function POST() {
|
||||
const auth = await requireAuth();
|
||||
if (auth.error) return auth.error;
|
||||
|
||||
cleanupTickets();
|
||||
|
||||
const ticket = randomUUID();
|
||||
ticketStore.set(ticket, {
|
||||
userId: auth.userId,
|
||||
expiresAt: Date.now() + TTL_30S,
|
||||
});
|
||||
|
||||
return NextResponse.json({ ticket }, { status: 201 });
|
||||
}
|
||||
33
web/src/lib/api.ts
Normal file
33
web/src/lib/api.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { getAuthenticatedUser } from '@/lib/auth';
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
/**
|
||||
* Authenticate the request and return userId or a 401 response.
|
||||
*/
|
||||
export async function requireAuth(): Promise<
|
||||
| { userId: string; error?: never }
|
||||
| { userId?: never; error: NextResponse }
|
||||
> {
|
||||
const user = await getAuthenticatedUser();
|
||||
if (!user) {
|
||||
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
|
||||
}
|
||||
return { userId: user.userId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a handler with JSON parse error handling.
|
||||
*/
|
||||
export async function parseBody<T>(request: Request, parse: (data: unknown) => T): Promise<
|
||||
| { data: T; error?: never }
|
||||
| { data?: never; error: NextResponse }
|
||||
> {
|
||||
try {
|
||||
const raw = await request.json();
|
||||
const data = parse(raw);
|
||||
return { data };
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : 'Invalid request body';
|
||||
return { error: NextResponse.json({ error: message }, { status: 400 }) };
|
||||
}
|
||||
}
|
||||
71
web/src/lib/validators.ts
Normal file
71
web/src/lib/validators.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
// Lists
|
||||
export const createListSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
color: z.string().max(20).optional(),
|
||||
icon: z.string().max(50).optional(),
|
||||
}).strict();
|
||||
|
||||
export const updateListSchema = z.object({
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
color: z.string().max(20).nullable().optional(),
|
||||
icon: z.string().max(50).nullable().optional(),
|
||||
position: z.number().int().min(0).optional(),
|
||||
isInbox: z.boolean().optional(),
|
||||
}).strict();
|
||||
|
||||
export const reorderSchema = z.object({
|
||||
ids: z.array(z.string().uuid()).min(1),
|
||||
}).strict();
|
||||
|
||||
// Tasks
|
||||
export const createTaskSchema = z.object({
|
||||
title: z.string().min(1).max(500),
|
||||
listId: z.string().uuid(),
|
||||
notes: z.string().max(5000).optional(),
|
||||
priority: z.number().int().min(0).max(3).optional(),
|
||||
dueDate: z.string().datetime().optional(),
|
||||
parentId: z.string().uuid().optional(),
|
||||
recurrence: z.string().max(100).optional(),
|
||||
}).strict();
|
||||
|
||||
export const updateTaskSchema = z.object({
|
||||
title: z.string().min(1).max(500).optional(),
|
||||
notes: z.string().max(5000).nullable().optional(),
|
||||
completed: z.boolean().optional(),
|
||||
priority: z.number().int().min(0).max(3).optional(),
|
||||
dueDate: z.string().datetime().nullable().optional(),
|
||||
listId: z.string().uuid().optional(),
|
||||
parentId: z.string().uuid().nullable().optional(),
|
||||
position: z.number().int().min(0).optional(),
|
||||
recurrence: z.string().max(100).nullable().optional(),
|
||||
}).strict();
|
||||
|
||||
// Tags
|
||||
export const createTagSchema = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
color: z.string().max(20).optional(),
|
||||
}).strict();
|
||||
|
||||
export const updateTagSchema = z.object({
|
||||
name: z.string().min(1).max(100).optional(),
|
||||
color: z.string().max(20).optional(),
|
||||
}).strict();
|
||||
|
||||
export const assignTagsSchema = z.object({
|
||||
tagIds: z.array(z.string().uuid()).min(1),
|
||||
}).strict();
|
||||
|
||||
// Sync
|
||||
export const syncPushSchema = z.object({
|
||||
operations: z.array(z.object({
|
||||
idempotencyKey: z.string().min(1).max(200),
|
||||
entityType: z.enum(['list', 'task', 'tag', 'taskTag']),
|
||||
entityId: z.string().uuid(),
|
||||
action: z.enum(['create', 'update', 'delete']),
|
||||
data: z.record(z.string(), z.unknown()).optional(),
|
||||
}).strict()),
|
||||
}).strict();
|
||||
|
||||
export type SyncOperation = z.infer<typeof syncPushSchema>['operations'][number];
|
||||
Loading…
Reference in a new issue