import { drizzle } from "drizzle-orm/bun-sqlite"; import { existsSync } from "node:fs"; import { readFileSync } from "node:fs"; import * as schema from "../database/schema"; interface FeedItem { user: { id: number; name: string; avatar: string | null; city: string | null; country: string | null; sex: string | null; weight: number | null; created_at: string; }; token: { id: number; user_id: number; refresh_token: string; access_token: string; expires_at: string; }; preferences: { tone: string[]; units: "Imperial" | "Metric"; enabled: boolean; language: string; }; } export default defineNitroPlugin(async () => { const config = useRuntimeConfig(); const feedPath = "tmp/feed.json"; if (!existsSync(feedPath)) { return; } console.log("Processing feed.json..."); const db = drizzle(config.databaseUrl, { schema }); const feed: FeedItem[] = JSON.parse(readFileSync(feedPath, "utf-8")); for (const item of feed) { const userId = String(item.user.id); await db .insert(schema.users) .values({ id: userId, name: item.user.name, avatar: item.user.avatar, city: item.user.city, country: item.user.country, sex: item.user.sex, weight: item.user.weight, createdAt: new Date(item.user.created_at), }) .onConflictDoUpdate({ target: schema.users.id, set: { name: item.user.name, avatar: item.user.avatar, city: item.user.city, country: item.user.country, sex: item.user.sex, weight: item.user.weight, }, }); await db .insert(schema.tokens) .values({ userId: userId, refreshToken: item.token.refresh_token, accessToken: item.token.access_token, expiresAt: new Date(item.token.expires_at), }) .onConflictDoUpdate({ target: schema.tokens.userId, set: { refreshToken: item.token.refresh_token, accessToken: item.token.access_token, expiresAt: new Date(item.token.expires_at), }, }); await db .insert(schema.preferences) .values({ userId: userId, data: { enabled: item.preferences.enabled, language: item.preferences.language, units: item.preferences.units, tone: item.preferences.tone, highlights: [], }, }) .onConflictDoUpdate({ target: schema.preferences.userId, set: { data: { enabled: item.preferences.enabled, language: item.preferences.language, units: item.preferences.units, tone: item.preferences.tone, highlights: [], }, }, }); } console.log(`Processed ${feed.length} feed items`); });