You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
106 lines
2.5 KiB
106 lines
2.5 KiB
import { dbGlobal } from "drizzle-pkg/lib/db";
|
|
import { ideas } from "drizzle-pkg/lib/schema/content";
|
|
import { desc, sql } from "drizzle-orm";
|
|
|
|
// ============ Types ============
|
|
export interface IdeaItem {
|
|
id: number;
|
|
author: string | null;
|
|
content: string;
|
|
platform: string | null;
|
|
color: string | null;
|
|
createdAt: Date;
|
|
}
|
|
|
|
export interface CreateIdeaInput {
|
|
author: string | null;
|
|
content: string;
|
|
platform?: string | null;
|
|
color?: string | null;
|
|
}
|
|
|
|
// ============ Color palette for random assignment ============
|
|
const IDEA_COLORS = [
|
|
"#cc785c", // primary coral
|
|
"#5db8a6", // accent teal
|
|
"#e8a55a", // accent amber
|
|
"#8b7ec8", // soft purple
|
|
"#6fa8dc", // soft blue
|
|
"#e07b7b", // soft red
|
|
"#7eb77f", // soft green
|
|
"#c9a0dc", // lavender
|
|
];
|
|
|
|
export function randomIdeaColor(): string {
|
|
return IDEA_COLORS[Math.floor(Math.random() * IDEA_COLORS.length)];
|
|
}
|
|
|
|
// ============ CRUD ============
|
|
|
|
export async function listIdeas(opts: {
|
|
page?: number;
|
|
pageSize?: number;
|
|
}): Promise<{ items: IdeaItem[]; total: number; page: number; pageSize: number; hasMore: boolean }> {
|
|
const page = opts.page ?? 1;
|
|
const pageSize = opts.pageSize ?? 30;
|
|
|
|
const [rows, countResult] = await Promise.all([
|
|
dbGlobal
|
|
.select()
|
|
.from(ideas)
|
|
.orderBy(desc(ideas.createdAt))
|
|
.limit(pageSize)
|
|
.offset((page - 1) * pageSize),
|
|
dbGlobal
|
|
.select({ count: sql<number>`count(*)` })
|
|
.from(ideas),
|
|
]);
|
|
|
|
// $count returns differently — use sql count as fallback
|
|
let total = 0;
|
|
if (countResult && countResult.length > 0) {
|
|
total = (countResult[0] as any).count ?? 0;
|
|
}
|
|
|
|
const items: IdeaItem[] = rows.map((row) => ({
|
|
id: row.id,
|
|
author: row.author,
|
|
content: row.content,
|
|
platform: row.platform,
|
|
color: row.color,
|
|
createdAt: row.createdAt,
|
|
}));
|
|
|
|
return {
|
|
items,
|
|
total,
|
|
page,
|
|
pageSize,
|
|
hasMore: page * pageSize < total,
|
|
};
|
|
}
|
|
|
|
export async function createIdea(input: CreateIdeaInput): Promise<IdeaItem> {
|
|
const color = input.color || randomIdeaColor();
|
|
|
|
const [inserted] = await dbGlobal
|
|
.insert(ideas)
|
|
.values({
|
|
author: input.author || '',
|
|
content: input.content,
|
|
platform: input.platform || null,
|
|
color,
|
|
})
|
|
.returning({ id: ideas.id });
|
|
|
|
if (!inserted) throw new Error("Failed to create idea");
|
|
|
|
return {
|
|
id: inserted.id,
|
|
author: input.author,
|
|
content: input.content,
|
|
platform: input.platform || null,
|
|
color,
|
|
createdAt: new Date(),
|
|
};
|
|
}
|
|
|