All files / src/controllers posts_controller.ts

88.23% Statements 30/34
66.66% Branches 4/6
100% Functions 4/4
88.23% Lines 30/34

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    4x 5x 5x 5x 2x 2x     3x 3x               4x 13x 13x 13x 11x     2x         4x 1x 1x 1x 1x 1x               4x 3x 3x 3x 3x 2x 1x     1x 1x     2x          
import postModel from '../models/posts_model';
 
const getAllPosts =  async (req, res) => {
    const senderFilter = req.query.sender;
    try{
        if(senderFilter){
            const posts = await postModel.find({sender: senderFilter});
            res.status(200).send(posts);
            
        } else{
            const posts = await postModel.find();
            res.status(200).send(posts);
        }
    } catch(error){
        res.status(400).send("Bad Request");
    }
 
}
 
const createPost = async (req, res) => {
    const post = req.body;
    try{
        const newPost = await postModel.create(post);
        res.status(201).send(newPost);
 
    }catch(error){
        res.status(400).send("Bad Request");
 
    }
}
 
const getPostById = async (req, res) => {
    const id = req.params.id;
    try {
        const post = await postModel.findById(id);
        Eif (!post) {
            return res.status(404).send('Post not found');
        }
        return res.status(200).send(post);
    } catch(error) {
        return res.status(400).send("Bad Request");
    }
}
 
const updatePostById = async (req, res) => {
    const id = req.params.id;
    const post = req.body;
    try {
        await new postModel(post).validate();
        const oldPost = await postModel.findByIdAndUpdate(id, post);
        Iif (oldPost == null) {
            res.status(404).send('Post not found');
        } else {
            post._id = oldPost._id;
            res.status(201).send(post);
        }        
    } catch(error) {
        res.status(400).send("Bad Request");
    }
}
 
export default {getAllPosts, createPost, getPostById, updatePostById};