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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import {PostModel } from '../models/posts_model';
import { IPost, PostData } from 'types/post_types';
import { Document } from 'mongoose';
const postToPostData = (post: Document<unknown, {}, IPost> & IPost): PostData => {
return { ...post.toJSON(), owner: post.owner.toString() };
};
/***
* 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();
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): Promise<PostData[]> => {
if (owner) {
const posts = await PostModel.find({ owner }).exec();
return posts.map(postToPostData);
} else {
const posts = await PostModel.find().exec();
return 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> => {
const deletedPost = await PostModel.findByIdAndDelete(postId).exec();
return deletedPost ? postToPostData(deletedPost) : null;
};
/**
* 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;
};
|