All files / src/services posts_service.ts

59.45% Statements 44/74
50% Branches 16/32
64.28% Functions 9/14
61.97% Lines 44/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223                            7x   47x 47x   47x                 7x                                     7x 12x 12x 12x 12x     12x               7x 7x 7x 7x     7x 6x 1x 1x 1x   5x 5x               7x 1x     1x 1x     1x 1x             7x 15x 15x               7x                                           7x 1x 1x                 7x 2x 2x                 7x 3x 3x     7x                                                 7x                     7x                                                        
import {PostModel } from '../models/posts_model';
import { IPost, PostData } from 'types/post_types';
import {ClientSession, Document} from 'mongoose';
import * as mongoose from 'mongoose';
import * as commentsService from './comments_service';
import * as usersService from './users_service';
import {UserModel} from "../models/user_model";
import likeModel from "../models/like_model";
import {CommentData} from "types/comment_types";
import {UserData} from 'types/user_types';
import * as chatService from './chat_api_service';
import {config} from "../config/config";
 
 
const postToPostData = async (post: Document<unknown, {}, IPost> & IPost): Promise<PostData> => {
    // Fetch the owner's profile image
    const user = await UserModel.findById(post.owner).lean();
    const profileImage = user?.imageFilename
 
    return { 
        ...post.toJSON(), 
        owner: post.owner.toString(),
        ownerProfileImage: profileImage, // Add the profile image to the post data
        ownerUsername: user?.username
    };
}
 
 
const addMisterAIComment = async (postId: string, postContent: string) => {
    let misterAI: UserData | null = await usersService.getUserByEmail('misterai@example.com');
    if (!misterAI) {
        misterAI = await usersService.addUser('misterai', 'securepassword', 'misterai@example.com', 'local');
    }
 
    const comment = await chatService.chatWithAI('You are an AI assistant tasked with providing the first comment on forum posts. Your responses should be relevant, engaging, and encourage further discussion, also must be short, and you must answer if you know the answer. Ensure your comments are appropriate for the content and tone of the post. Also must answer in the language of the user post. answer short answers. dont ask questions to follow up', [postContent]);
    const commentData: CommentData = { postId, owner: misterAI.id, content: comment };
    const savedComment = await commentsService.addComment(commentData);
    return savedComment;
};
 
 
 
/***
    * Add a new post
    * @param postData - The post data to be added
    * @returns The added post
    */
export const addPost = async (postData: PostData): Promise<PostData> => {
    const newPost = new PostModel(postData);
    await newPost.save();
    const turn = config.chatAi.turned_on();
    Iif(postData.content && turn) {
        addMisterAIComment(newPost.id, postData.content);
    }
    return postToPostData(newPost);
};
 
/***
    * Get all posts
    * @param owner - The owner of the posts to be fetched
    * @returns The list of posts
    */
export const getPosts = async (owner?: string, skip = 0, limit = 10): Promise<PostData[]> => {
    const query = owner ? { owner } : {};
    const posts = await PostModel.find(query).skip(skip).limit(limit).exec();
    return Promise.all(posts.map(postToPostData));
};
 
export const getTotalPosts = async (owner?: string, username?: string): Promise<number> => {
    if (username) {
        const user = await UserModel.findOne({ username }).select('_id').lean().exec();
        Iif (!user) return 0;
        return PostModel.countDocuments({ owner: user._id }).exec();
    }
    const query = owner ? { owner } : {};
    return PostModel.countDocuments(query).exec();
};
 
/***
 * Get posts by username
 * @param username - The username of the posts to be fetched
 * @returns The list of posts
 */
export const getPostsByUsername = async (username: string): Promise<PostData[]> => {
    Iif (!username) return [];
 
    // Find the user first
    const user = await UserModel.findOne({ username }).select('_id').lean().exec();
    Iif (!user) return [];
 
    // Then find posts with that user's ID
    const posts = await PostModel.find({ owner: user._id }).exec();
    return Promise.all(posts.map(postToPostData));
};
 
/**
 * Get a post by ID
 * @param postId
 */
export const getPostById = async (postId: string): Promise<PostData | null> => {
    const post = await PostModel.findById(postId).exec();
    return post ? postToPostData(post) : null;
};
 
 
/**
 * Delete a post by ID
 * @param postId
 */
export const deletePostById = async (postId: string): Promise<PostData | null> => {
    try {
        // Delete comments associated with the post
        await commentsService.deleteCommentsByPostId(postId);
 
        // Delete the post
        const post = await PostModel.findByIdAndDelete(postId).exec();
 
        // Return the deleted post data
        return post ? await postToPostData(post) : null;
    } catch (error) {
        console.error("Error deleting post:", error);
        throw error;
    }
};
 
 
/**
 * Update a post
 * @param postId
 * @param postData
 */
export const updatePost = async (postId: string, postData: Partial<PostData>): Promise<PostData | null> => {
    const updatedPost = await PostModel.findByIdAndUpdate(postId, { ...postData }, { new: true, runValidators: true }).exec();
    return updatedPost ? postToPostData(updatedPost) : null;
};
 
/**
 * Check if a post is owned by a specific user
 * @param postId
 * @param ownerId
 * @returns boolean indicating ownership
 */
export const isPostOwnedByUser = async (postId: string, ownerId: string): Promise<boolean> => {
    const post = await PostModel.findById(postId).exec();
    return post ? post.owner.toString() === ownerId : false;
};
 
 
/**
 * Check if a post exists by ID
 * @param postId
 * @returns boolean indicating existence
 */
export const postExists = async (postId: string): Promise<boolean> => {
    const post = await PostModel.exists({ _id: postId }).exec();
    return post !== null;
};
 
export const updatePostLike = async (postId: string, booleanValue: string, userId: string): Promise<void> => {
    const post = await getPostById(postId);
    if(post != null) {
        if (booleanValue) {
            // Upsert
            await likeModel.updateOne({
                    userId: new mongoose.Types.ObjectId(userId),
                    postId: post?.id
                },
                {},
                {upsert: true}
            );
        } else {
            // Delete like document if exists
            await likeModel.findOneAndDelete({
                userId: new mongoose.Types.ObjectId(userId),
                postId: post?.id
            });
        }
    }
    else{
        throw new Error("Post not found")
    }
}
 
export const getPostLikesCount = async (postId: string): Promise<number> => {
    try {
        // Count the number of likes for the given post ID
        const likesCount = await likeModel.countDocuments({ postId: new mongoose.Types.ObjectId(postId) }).exec();
        return likesCount;
    } catch (error) {
        console.error(`Error fetching likes count for post ${postId}:`, error);
        throw new Error('Failed to fetch likes count');
    }
};
 
export const getLikedPostsByUser = async (userId: string) => {
    const likedPostsByUserId = await likeModel.aggregate([
        {
            $match: {
                userId: new mongoose.Types.ObjectId(userId)
            }
        },
        {
            $lookup: {
                from: 'posts',
                localField: 'postId',
                foreignField: '_id',
                as: 'post'
            }
        },
        {
            $unwind: {
                path: '$post'
            }
        },
        {
            $replaceRoot: {
                newRoot: '$post'
            }
        }
    ]);
    return likedPostsByUserId;
}