'use server' import fs from 'fs/promises' import path from 'path' import env from '@/lib/env' import resolveFilePath from '@/lib/file' export interface MarkLinkI { title: string url: string blank?: boolean } export interface MarkCardI { id: string userId?: string title: string shortDescription: string detailedDescription?: string links: MarkLinkI[] publicUrl?: string } const rootPath = path.join(process.cwd(), env('CARD_FILE_PATH')) // Waring export async function getBasePath(userId?: string) { return path.join(userId ? userId : '', 'markcard') } export async function getPath(userId?: string, fileUrl?: string[]) { return resolveFilePath(fileUrl, path.join(rootPath, await getBasePath(userId)), ['.json'], ['index.json']) } async function writeInFile(cards: MarkCardI[], filePath: string) { const fileDir = path.dirname(filePath) try { await fs.access(fileDir) } catch { await fs.mkdir(fileDir, { recursive: true }) } fs.writeFile(filePath, JSON.stringify(cards, null, 2), 'utf8') } async function readFromFile(filePath: string): Promise { await fs.access(filePath) return JSON.parse(await fs.readFile(filePath, 'utf8')) } export async function getCards(filePath:string): Promise { try { return await readFromFile(filePath) } catch { return undefined } } export async function addCard(card: Omit, filePath: string): Promise { const cards = await getCards(filePath) if (cards && cards.length > 20) { throw new Error('Maximum number of cards reached') } const newCard = { ...card, id: String(cards ? cards.length + 1 : 0) } if (!cards) { writeInFile([newCard], filePath) } else { cards.push(newCard) writeInFile(cards, filePath) } return newCard } export async function updateCard(updatedCard: Partial, cardId: string, filePath: string): Promise { const cards = await getCards(filePath) if (!cards) { return null } const index = cards.findIndex(card => card.id === cardId) if (index === -1) return null cards[index] = { ...cards[index], ...updatedCard } writeInFile(cards, filePath) return cards[index] } // export function deleteCard(id: string): boolean { // const initialLength = cards.length // cards = cards.filter(card => card.id !== id) // return cards.length < initialLength // }