64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
import { and, desc, eq } from 'drizzle-orm';
|
|
import type { WatchlistItem } from '@/lib/types';
|
|
import { db } from '@/lib/server/db';
|
|
import { watchlistItem } from '@/lib/server/db/schema';
|
|
|
|
type WatchlistRow = typeof watchlistItem.$inferSelect;
|
|
|
|
function toWatchlistItem(row: WatchlistRow): WatchlistItem {
|
|
return {
|
|
id: row.id,
|
|
user_id: row.user_id,
|
|
ticker: row.ticker,
|
|
company_name: row.company_name,
|
|
sector: row.sector,
|
|
created_at: row.created_at
|
|
};
|
|
}
|
|
|
|
export async function listWatchlistItems(userId: string) {
|
|
const rows = await db
|
|
.select()
|
|
.from(watchlistItem)
|
|
.where(eq(watchlistItem.user_id, userId))
|
|
.orderBy(desc(watchlistItem.created_at));
|
|
|
|
return rows.map(toWatchlistItem);
|
|
}
|
|
|
|
export async function upsertWatchlistItemRecord(input: {
|
|
userId: string;
|
|
ticker: string;
|
|
companyName: string;
|
|
sector?: string;
|
|
}) {
|
|
const [row] = await db
|
|
.insert(watchlistItem)
|
|
.values({
|
|
user_id: input.userId,
|
|
ticker: input.ticker,
|
|
company_name: input.companyName,
|
|
sector: input.sector?.trim() ? input.sector.trim() : null,
|
|
created_at: new Date().toISOString()
|
|
})
|
|
.onConflictDoUpdate({
|
|
target: [watchlistItem.user_id, watchlistItem.ticker],
|
|
set: {
|
|
company_name: input.companyName,
|
|
sector: input.sector?.trim() ? input.sector.trim() : null
|
|
}
|
|
})
|
|
.returning();
|
|
|
|
return toWatchlistItem(row);
|
|
}
|
|
|
|
export async function deleteWatchlistItemRecord(userId: string, id: number) {
|
|
const removed = await db
|
|
.delete(watchlistItem)
|
|
.where(and(eq(watchlistItem.user_id, userId), eq(watchlistItem.id, id)))
|
|
.returning({ id: watchlistItem.id });
|
|
|
|
return removed.length > 0;
|
|
}
|