Files
soul-yongping/lib/prisma-helpers.ts

141 lines
3.2 KiB
TypeScript
Raw Normal View History

/**
* Prisma
*
*/
import { prisma } from '@/lib/prisma'
/**
*
*/
export async function getPrismaConfig(key: string): Promise<any> {
try {
const config = await prisma.system_config.findUnique({
where: { config_key: key }
})
return config?.config_value
} catch (e) {
console.warn(`[Config] 读取配置 ${key} 失败:`, e)
return null
}
}
/**
*
*/
export async function setPrismaConfig(key: string, value: any, description?: string): Promise<void> {
await prisma.system_config.upsert({
where: { config_key: key },
update: {
config_value: value,
description: description || null,
updated_at: new Date()
},
create: {
config_key: key,
config_value: value,
description: description || null
}
})
}
/**
* ID openId
*/
export async function findUserByIdOrOpenId(userId?: string, openId?: string) {
if (!userId && !openId) return null
return await prisma.users.findFirst({
where: userId ? { id: userId } : { open_id: openId }
})
}
/**
*
*/
export async function findUsersByIds(userIds: string[]) {
return await prisma.users.findMany({
where: { id: { in: userIds } }
})
}
/**
*
*/
export async function trackUserAction(
userId: string,
action: string,
chapterId?: string,
target?: string,
extraData?: any
) {
try {
await prisma.user_tracks.create({
data: {
id: `track_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
user_id: userId,
action,
chapter_id: chapterId || null,
target: target || null,
extra_data: extraData || null
}
})
} catch (e) {
console.error('[Track] 记录失败:', e)
}
}
/**
*
*/
export async function hasUserPurchasedChapter(userId: string, chapterId: string): Promise<boolean> {
const user = await prisma.users.findUnique({
where: { id: userId },
select: { has_full_book: true, purchased_sections: true }
})
if (!user) return false
if (user.has_full_book) return true
const purchasedSections = user.purchased_sections as any
if (Array.isArray(purchasedSections)) {
return purchasedSections.includes(chapterId)
}
return false
}
/**
*
*/
export async function getUserPurchasedChapters(userId: string): Promise<string[]> {
const user = await prisma.users.findUnique({
where: { id: userId },
select: { purchased_sections: true }
})
const sections = user?.purchased_sections as any
return Array.isArray(sections) ? sections : []
}
/**
*
*/
export async function addUserPurchasedChapter(userId: string, chapterId: string): Promise<void> {
const user = await prisma.users.findUnique({
where: { id: userId },
select: { purchased_sections: true }
})
const sections = user?.purchased_sections as any
const purchased = Array.isArray(sections) ? sections : []
if (!purchased.includes(chapterId)) {
purchased.push(chapterId)
await prisma.users.update({
where: { id: userId },
data: { purchased_sections: purchased }
})
}
}