All files postsRouter.ts

100% Statements 36/36
100% Branches 2/2
100% Functions 6/6
100% Lines 29/29

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    1x 1x   1x   1x     1x 3x   1x       1x 4x   4x 4x   4x       1x 2x   2x 2x   1x   1x       1x 1x 1x   1x 1x   1x       1x 1x   1x   1x     1x  
// This file contains the EXPRESS router 
 
import express, { Request, Response } from "express";
import { Post } from "./post";
 
const postsRouter = express.Router();
 
const postList = [];
 
/* GET posts listing. */
postsRouter.get("/", (_req: Request, res: Response) => {
  const existedPosts = postList.filter((post) => typeof post != "undefined");
 
  res.json(existedPosts);
});
 
/* POST create post. */
postsRouter.post("/", (req: Request, res: Response) => {
  const { title, description, category } = req.body; // destructuring data from request
 
  const post = new Post(postList.length, title, description, category); // create Post
  postList.push(post); // add Post to postList
 
  res.json({ done: true, postId: post.id }); // send positive response in JSON format
});
 
/* GET return post */
postsRouter.get("/:id", (req: Request, res: Response) => {
  const postId = parseInt(req.params.id); // get post id from path
 
  const post = postList[postId]; // get post from postList
  if (typeof post !== "undefined") {
    // if post exists in postList
    return res.json({ done: true, post }); // send positive response in JSON format
  }
  res.json({ done: false }); // send negative response in JSON format
});
 
/* PUT update post. */
postsRouter.put("/:id", (req: Request, res: Response) => {
  const { title, description, category } = req.body; // destructuring data from request
  const postId = parseInt(req.params.id, 10); // get post id from path
 
  const post = new Post(postId, title, description, category); // create Post
  postList[postId] = post; // replace post with the id (new one will be created if id was free)
 
  res.json({ done: true, postId }); // send positive response in JSON format
});
 
/* DELETE delete post. */
postsRouter.delete("/:id", (req: Request, res: Response) => {
  const postId = parseInt(req.params.id); // get post id from path
 
  delete postList[postId]; // delete post with that id from the list
 
  res.json({ done: true, postId }); // send positive response in JSON format
});
 
export { postsRouter };