first commit
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export const getAllComments = async (postSlug?: string) => {
|
||||
try {
|
||||
const comments = await prisma.comment.findMany({
|
||||
orderBy: [{ createdAt: 'desc' }],
|
||||
where: {
|
||||
...(postSlug && { postSlug: postSlug })
|
||||
},
|
||||
include: { user: true }
|
||||
})
|
||||
return comments
|
||||
} catch (error) {
|
||||
console.error('Error fetching comments:', error)
|
||||
throw new Error('Error fetching comments')
|
||||
}
|
||||
}
|
||||
|
||||
export const createComment = async (body: any, userEmail: any, session: any) => {
|
||||
if (!session) {
|
||||
throw new Error('Not Authenticated')
|
||||
}
|
||||
|
||||
try {
|
||||
const comment = await prisma.comment.create({
|
||||
data: { description: body.description, postSlug: body.postSlug, userEmail: userEmail }
|
||||
})
|
||||
return comment
|
||||
} catch (error) {
|
||||
console.error('Error creating comment:', error)
|
||||
throw new Error('Error creating comment')
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteComment = async (id: string) => {
|
||||
await prisma.comment.delete({
|
||||
where: {
|
||||
id: id
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export const addFavorite = async (postId: any, userEmail: any, session: any) => {
|
||||
try {
|
||||
if (!session) {
|
||||
throw new Error('Not Authenticated')
|
||||
}
|
||||
const existingFavorite = await prisma.favorite.findUnique({
|
||||
where: { postId_userEmail: { postId, userEmail } }
|
||||
})
|
||||
if (existingFavorite) {
|
||||
throw new Error('El usuario ya marcó este post como favorito.')
|
||||
}
|
||||
await prisma.favorite.create({
|
||||
data: {
|
||||
postId,
|
||||
userEmail
|
||||
}
|
||||
})
|
||||
const updatedFavorites = await prisma.post
|
||||
.findUnique({
|
||||
where: { id: postId }
|
||||
})
|
||||
.Favorite()
|
||||
|
||||
return updatedFavorites
|
||||
} catch (error) {
|
||||
console.error('Error al añadir a favoritos:', error)
|
||||
throw new Error('Error al añadir a favoritos')
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteFavorite = async (postId: any, userEmail: string, session: any) => {
|
||||
try {
|
||||
// Verificar si el usuario ha marcado el post como favorito
|
||||
const existingFavorite = await prisma.favorite.findUnique({
|
||||
where: { postId_userEmail: { postId, userEmail } }
|
||||
})
|
||||
if (!existingFavorite) {
|
||||
throw new Error('El usuario no ha marcado este post como favorito.')
|
||||
}
|
||||
// Eliminar de favoritos
|
||||
await prisma.favorite.delete({
|
||||
where: { postId_userEmail: { postId, userEmail } }
|
||||
})
|
||||
|
||||
const updatedFavorites = await prisma.post
|
||||
.findUnique({
|
||||
where: { id: postId }
|
||||
})
|
||||
.Favorite()
|
||||
|
||||
return updatedFavorites
|
||||
} catch (error) {
|
||||
console.error('Error al quitar de favoritos:', error)
|
||||
throw new Error('Error al quitar de favoritos')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export const addLike = async (postId: any, userEmail: any, session: any) => {
|
||||
try {
|
||||
if (!session) {
|
||||
throw new Error('Not Authenticated')
|
||||
}
|
||||
const existingLike = await prisma.like.findUnique({
|
||||
where: { postId_userEmail: { postId, userEmail } }
|
||||
})
|
||||
if (existingLike) {
|
||||
throw new Error('El usuario ya dio like a este post.')
|
||||
}
|
||||
await prisma.like.create({
|
||||
data: {
|
||||
postId,
|
||||
userEmail
|
||||
}
|
||||
})
|
||||
const updatedLikes = await prisma.post
|
||||
.findUnique({
|
||||
where: { id: postId }
|
||||
})
|
||||
.Like()
|
||||
|
||||
return updatedLikes
|
||||
} catch (error) {
|
||||
console.error('Error al añadir el like:', error)
|
||||
throw new Error('Error al añadir el like')
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteLike = async (postId: any, userEmail: string, session: any) => {
|
||||
try {
|
||||
// Verificar si el usuario ha dado like al post
|
||||
const existingLike = await prisma.like.findUnique({
|
||||
where: { postId_userEmail: { postId, userEmail } }
|
||||
})
|
||||
if (!existingLike) {
|
||||
throw new Error('El usuario no ha dado like a este post.')
|
||||
}
|
||||
// Eliminar el like
|
||||
await prisma.like.delete({
|
||||
where: { postId_userEmail: { postId, userEmail } }
|
||||
})
|
||||
|
||||
const updatedLikes = await prisma.post
|
||||
.findUnique({
|
||||
where: { id: postId }
|
||||
})
|
||||
.Like()
|
||||
|
||||
return updatedLikes
|
||||
} catch (error) {
|
||||
console.error('Error al quitar el like:', error)
|
||||
throw new Error('Error al quitar el like')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export const deletePost = async (slug: string) => {
|
||||
try {
|
||||
const post = await prisma.post.findUnique({
|
||||
where: {
|
||||
slug: slug
|
||||
},
|
||||
include: {
|
||||
comments: true
|
||||
}
|
||||
})
|
||||
if (!post) {
|
||||
throw new Error('Post not found')
|
||||
}
|
||||
await prisma.like.deleteMany({
|
||||
where: {
|
||||
postId: post.id
|
||||
}
|
||||
})
|
||||
await prisma.comment.deleteMany({
|
||||
where: {
|
||||
postSlug: slug
|
||||
}
|
||||
})
|
||||
await prisma.post.delete({
|
||||
where: {
|
||||
slug: slug
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error, 'Error deleting post')
|
||||
throw new Error('Error deleting post')
|
||||
}
|
||||
}
|
||||
|
||||
export const editPost = async (slug: string, newData: any) => {
|
||||
try {
|
||||
// Buscar el post que se va a editar
|
||||
const existingPost = await prisma.post.findUnique({
|
||||
where: {
|
||||
slug: slug
|
||||
}
|
||||
})
|
||||
// Verificar si el post existe
|
||||
if (!existingPost) {
|
||||
throw new Error('Post not found')
|
||||
}
|
||||
// Actualizar el post con los nuevos datos
|
||||
const updatedPost = await prisma.post.update({
|
||||
where: {
|
||||
slug: slug
|
||||
},
|
||||
data: {
|
||||
...newData
|
||||
// Tags: {
|
||||
// set: newData.Tags.map((tag: any) => ({ id: tag.id }))
|
||||
// }
|
||||
}
|
||||
})
|
||||
|
||||
return updatedPost
|
||||
} catch (error) {
|
||||
console.error(error, 'Error editing post')
|
||||
throw new Error('Error editing post')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// This is your Prisma schema file,
|
||||
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "mongodb"
|
||||
url = env("MONGODB_URI")
|
||||
}
|
||||
|
||||
// datasource db {
|
||||
// provider = "mongodb"
|
||||
// url = env("DATABASE_URL")
|
||||
// }
|
||||
|
||||
model Account {
|
||||
id String @id @default(cuid()) @map("_id")
|
||||
userId String
|
||||
type String
|
||||
provider String
|
||||
providerAccountId String
|
||||
refresh_token String?
|
||||
access_token String?
|
||||
expires_at Int?
|
||||
token_type String?
|
||||
scope String?
|
||||
id_token String?
|
||||
session_state String?
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([provider, providerAccountId])
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(cuid()) @map("_id")
|
||||
sessionToken String @unique
|
||||
userId String
|
||||
expires DateTime
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid()) @map("_id")
|
||||
name String?
|
||||
email String @unique
|
||||
emailVerified DateTime?
|
||||
image String?
|
||||
isAdmin Boolean @unique @default(false)
|
||||
accounts Account[]
|
||||
sessions Session[]
|
||||
Post Post[]
|
||||
Like Like[]
|
||||
Comment Comment[]
|
||||
Favorite Favorite[]
|
||||
}
|
||||
|
||||
model VerificationToken {
|
||||
identifier String @id @map("_id")
|
||||
token String @unique
|
||||
expires DateTime
|
||||
|
||||
@@unique([identifier, token])
|
||||
}
|
||||
|
||||
model Category {
|
||||
id String @id @default(cuid()) @map("_id")
|
||||
slug String @unique
|
||||
title String
|
||||
img String?
|
||||
color String?
|
||||
Posts Post[]
|
||||
Comment Comment[]
|
||||
}
|
||||
|
||||
// model Tag {
|
||||
// id String @id @default(cuid()) @map("_id")
|
||||
// name String @unique
|
||||
// slug String @unique
|
||||
// color String?
|
||||
// // Posts PostTag[]
|
||||
// Post Post? @relation(fields: [postId], references: [id])
|
||||
// postId String?
|
||||
// }
|
||||
|
||||
// model PostTag {
|
||||
// id String @id @default(cuid()) @map("_id")
|
||||
// postId String
|
||||
// tagId String
|
||||
// post Post @relation(fields: [postId], references: [id])
|
||||
// tag Tag @relation(fields: [tagId], references: [id])
|
||||
|
||||
// @@unique([postId, tagId])
|
||||
// }
|
||||
|
||||
model Post {
|
||||
id String @id @default(cuid()) @map("_id")
|
||||
slug String @unique
|
||||
title String
|
||||
description String
|
||||
img String?
|
||||
views Int @default(0)
|
||||
catSlug String?
|
||||
Category Category? @relation(fields: [catSlug], references: [slug])
|
||||
userEmail String
|
||||
user User @relation(fields: [userEmail], references: [email], onDelete: Cascade)
|
||||
Like Like[]
|
||||
comments Comment[]
|
||||
url String?
|
||||
twitterShareCount Int @default(0)
|
||||
whatsappShareCount Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
Favorite Favorite[]
|
||||
// PostTag PostTag[]
|
||||
// Tags Tag[]
|
||||
}
|
||||
|
||||
model Like {
|
||||
id String @id @default(cuid()) @map("_id")
|
||||
postId String
|
||||
post Post @relation(fields: [postId], references: [id])
|
||||
userEmail String
|
||||
user User @relation(fields: [userEmail], references: [email], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([postId, userEmail])
|
||||
}
|
||||
|
||||
model Favorite {
|
||||
id String @id @default(cuid()) @map("_id")
|
||||
postId String
|
||||
post Post @relation(fields: [postId], references: [id])
|
||||
userEmail String
|
||||
user User @relation(fields: [userEmail], references: [email], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([postId, userEmail])
|
||||
}
|
||||
|
||||
model Comment {
|
||||
id String @id @default(cuid()) @map("_id")
|
||||
createdAt DateTime @default(now())
|
||||
description String
|
||||
userEmail String
|
||||
user User @relation(fields: [userEmail], references: [email], onDelete: Cascade)
|
||||
postSlug String
|
||||
post Post @relation(fields: [postSlug], references: [slug])
|
||||
|
||||
Category Category? @relation(fields: [categoryId], references: [id])
|
||||
categoryId String?
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export const getAllStats = async () => {
|
||||
try {
|
||||
const totalPosts = await prisma.post.count()
|
||||
const totalUsers = await prisma.user.count()
|
||||
const totalViews = await prisma.post.aggregate({ _sum: { views: true } })
|
||||
const totalShares = await prisma.post.aggregate({
|
||||
_sum: { twitterShareCount: true, whatsappShareCount: true }
|
||||
})
|
||||
|
||||
return {
|
||||
totalPosts,
|
||||
totalUsers,
|
||||
totalViews: totalViews._sum || 0,
|
||||
totalShares: totalShares._sum || 0
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching statistics:', error)
|
||||
throw new Error('Error fetching statistics')
|
||||
} finally {
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// import { PrismaClient } from '@prisma/client'
|
||||
// const prisma = new PrismaClient()
|
||||
|
||||
// //CREAR NUEVO TAG
|
||||
|
||||
// export const createTag = async (tagData: { name: string; slug: string; color?: string }) => {
|
||||
// try {
|
||||
// const normalizedTagSlug = tagData.slug.toLowerCase()
|
||||
// const existingTagMinus = await prisma.tag.findUnique({
|
||||
// where: { slug: normalizedTagSlug }
|
||||
// })
|
||||
|
||||
// if (existingTagMinus) {
|
||||
// console.error(`Error al crear el Tag: El SLUG "${tagData.slug}" ya está en uso.`)
|
||||
// throw new Error(`Error al crear el Tag: El SLUG "${tagData.slug}" ya está en uso.`)
|
||||
// }
|
||||
|
||||
// const newTag = await prisma.tag.create({
|
||||
// data: { ...tagData, slug: normalizedTagSlug }
|
||||
// })
|
||||
|
||||
// return newTag
|
||||
// } catch (error) {
|
||||
// console.error('Error al crear el Tag:', error)
|
||||
// throw new Error('Error al crear el Tag')
|
||||
// }
|
||||
// }
|
||||
|
||||
// // OBTENER TODOS LOS TAGS
|
||||
|
||||
// export const getAllTags = async () => {
|
||||
// try {
|
||||
// const tags = await prisma.tag.findMany()
|
||||
// return tags
|
||||
// } catch (error) {
|
||||
// console.error('Error al obtener todos los Tags:', error)
|
||||
// throw new Error('Error al obtener todos los Tags')
|
||||
// }
|
||||
// }
|
||||
|
||||
// // OBTENER UN TAG POR SU ID
|
||||
|
||||
// export const getTagById = async (tagId: string) => {
|
||||
// try {
|
||||
// const tag = await prisma.tag.findUnique({
|
||||
// where: { id: tagId }
|
||||
// })
|
||||
// return tag
|
||||
// } catch (error) {
|
||||
// console.error('Error al obtener el Tag por ID:', error)
|
||||
// throw new Error('Error al obtener el Tag por ID')
|
||||
// }
|
||||
// }
|
||||
|
||||
// //ACTUALIZAR UN TAG
|
||||
|
||||
// export const updateTag = async (tagData: { id: string; name?: string; slug?: string; color?: string }) => {
|
||||
// try {
|
||||
// const updatedTag = await prisma.tag.update({
|
||||
// where: { id: tagData.id },
|
||||
// data: { name: tagData.name, slug: tagData.slug, color: tagData.color }
|
||||
// })
|
||||
// return updatedTag
|
||||
// } catch (error) {
|
||||
// console.error('Error al actualizar el Tag:', error)
|
||||
// throw new Error('Error al actualizar el Tag')
|
||||
// }
|
||||
// }
|
||||
|
||||
// // ELIMINAR UN TAG
|
||||
|
||||
// export const deleteTag = async (tagId: string) => {
|
||||
// try {
|
||||
// const deletedTag = await prisma.tag.delete({
|
||||
// where: { id: tagId }
|
||||
// })
|
||||
// return deletedTag
|
||||
// } catch (error) {
|
||||
// console.error('Error al eliminar el Tag:', error)
|
||||
// throw new Error('Error al eliminar el Tag')
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,93 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export const getAllUsers = async () => {
|
||||
try {
|
||||
const users = await prisma.user.findMany()
|
||||
return users
|
||||
} catch (error) {
|
||||
console.error('Error fetching users:', error)
|
||||
throw new Error('Error fetching users')
|
||||
}
|
||||
}
|
||||
export const getUserByEmail = async (email: string) => {
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
email: email
|
||||
},
|
||||
include: {
|
||||
Like: true,
|
||||
Favorite: true
|
||||
}
|
||||
})
|
||||
return user
|
||||
} catch (error) {
|
||||
console.error('Error fetching user by ID:', error)
|
||||
throw new Error('Error fetching user by ID')
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteUserByEmail = async (email: string) => {
|
||||
try {
|
||||
const userDeleted = await prisma.user.delete({
|
||||
where: {
|
||||
email: email
|
||||
},
|
||||
include: {
|
||||
Like: true,
|
||||
Comment: true,
|
||||
sessions: true,
|
||||
accounts: true
|
||||
}
|
||||
})
|
||||
|
||||
return userDeleted
|
||||
} catch (error) {
|
||||
console.error(`Error deleting user with email ${email}:`, error)
|
||||
throw new Error(`Unable to delete user with email ${email}`)
|
||||
}
|
||||
}
|
||||
|
||||
export const updateUserByEmail = async (email: string, newData: any) => {
|
||||
try {
|
||||
const { name } = newData
|
||||
if (name) {
|
||||
const existingUserWithSameName = await prisma.user.findFirst({
|
||||
where: {
|
||||
name: name,
|
||||
email: { not: email }
|
||||
}
|
||||
})
|
||||
|
||||
if (existingUserWithSameName) {
|
||||
return { success: false, status: 409, error: `Name ${name} is already in use by another user` }
|
||||
}
|
||||
}
|
||||
// Verificar si el usuario existe
|
||||
const existingUser = await prisma.user.findUnique({
|
||||
where: {
|
||||
email: email
|
||||
}
|
||||
})
|
||||
|
||||
if (!existingUser) {
|
||||
return { status: 404, error: `User with email ${email} not found` }
|
||||
}
|
||||
|
||||
// Actualizar el usuario con los nuevos datos
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: {
|
||||
email: email
|
||||
},
|
||||
data: newData
|
||||
})
|
||||
|
||||
return updatedUser
|
||||
} catch (error) {
|
||||
console.error(`Error updating user with email ${email}:`, error)
|
||||
return { status: 500, error: `Unable to update user with email ${email}` }
|
||||
} finally {
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user