ZZY 73917d6001 dev feat(markcard, static): 实现书签卡片功能和静态资源获取
- 书签卡片相关的组件和页面
- 实现书签数据的获取、添加、编辑和删除功能
- 添加用户验证和权限控制
- 优化页面布局和样式
2024-12-22 15:21:07 +08:00

92 lines
2.4 KiB
TypeScript

'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<MarkCardI[]> {
await fs.access(filePath)
return JSON.parse(await fs.readFile(filePath, 'utf8'))
}
export async function getCards(filePath:string): Promise<MarkCardI[] | undefined> {
try {
return await readFromFile(filePath)
} catch {
return undefined
}
}
export async function addCard(card: Omit<MarkCardI, 'id'>, filePath: string): Promise<MarkCardI> {
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<MarkCardI>,
cardId: string,
filePath: string): Promise<MarkCardI | null> {
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
// }