All files / src/services comments_service.ts

88.88% Statements 24/27
50% Branches 3/6
77.77% Functions 7/9
88.88% Lines 24/27

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          7x 31x 31x     7x 8x 8x 8x     7x             7x 3x 3x     7x 4x 4x     7x 3x 3x     7x 2x 2x     7x 1x 1x     7x    
import { CommentModel } from '../models/comments_model';
import { IComment, CommentData } from 'types/comment_types';
import { Document } from 'mongoose';
import { UserModel } from '../models/user_model';
 
const commentToCommentData = async (comment: Document<unknown, {}, IComment> & IComment): Promise<CommentData> => {
    const user = await UserModel.findById(comment.owner).select('imageFilename').exec();
    return { ...comment.toJSON(), owner: comment.owner.toString(), postId: comment.postId.toString(), ownerProfileImage: user?.imageFilename };
};
 
export const addComment = async (commentData: CommentData): Promise<CommentData> => {
    const comment = new CommentModel(commentData);
    await comment.save();
    return commentToCommentData(comment);
};
 
export const getCommentsWithAuthorsByPostId = async (postId: string): Promise<CommentData[]> => {
    const comments = await CommentModel.find({ postId })
        .populate('author', 'username email')
        .exec();
    return Promise.all(comments.map(commentToCommentData));
};
 
export const getCommentsByPostId = async (postId: string): Promise<CommentData[]> => {
    const comments = await CommentModel.find({ postId }).exec();
    return Promise.all(comments.map(commentToCommentData));
};
 
export const getAllComments = async (): Promise<CommentData[]> => {
    const comments = await CommentModel.find().exec();
    return Promise.all(comments.map(commentToCommentData));
};
 
export const updateComment = async (commentId: string, commentData: Partial<CommentData>): Promise<CommentData | null> => {
    const comment = await CommentModel.findByIdAndUpdate(commentId, {content: commentData?.content}, { new: true }).exec();
    return comment ? commentToCommentData(comment) : null;
};
 
export const deleteComment = async (commentId: string): Promise<CommentData | null> => {
    const comment = await CommentModel.findByIdAndDelete(commentId).exec();
    return comment ? commentToCommentData(comment) : null;
};
 
export const getCommentById = async (commentId: string): Promise<CommentData | null> => {
    const comment = await CommentModel.findById(commentId).exec();
    return comment ? commentToCommentData(comment) : null;
};
 
export const deleteCommentsByPostId = async (postId: string): Promise<void> => {
    await CommentModel.deleteMany({ postId }).exec();
};