Правильно ли созданы эти конечные точки (Node, Express, Postgres, Knex)?

#javascript #node.js #postgresql #express #knex.js

Вопрос:

Я работаю над RESTful API, где мне нужно было создать конечные точки GET и POST и правильно связать их с файлом маршрутизатора. У меня есть моя controller.js файл, router.js файл, и service.js файл полностью настроен, но я в основном хочу знать, правильно ли эти функции выглядят в моем controller.js файл, и если мой router.js файл записан правильно.

todo.controller.js файл:

 const service = require("./todo.service"); const path = require("path"); const xss = require("xss");  //middleware const serializeTodo = (todo) =gt; ({  id: todo.id,  title: xss(todo.title),  completed: todo.completed, });  function idIsValid(req, res, next) {  if (isNaN(parseInt(req.params.todo_id))) {  return res.status(404).json({  error: { message: `Invalid id` },  });  } else {  next();  } }  //CRUD methods async function create(req, res) {  const data = await service.create(req.body.data);  res.status(201).json({ data }); }  async function read(req, res) {  const todo = await service.read(req.params.todo_id);  if (!todo) {  return res.status(404).json({  error: { message: `Todo doesn't exist` },  });  }  res.json(serializeTodo(todo)); }  async function update(req, res) {  const { todo_id } = req.params;  const { title, completed } = req.body;  const todoToUpdate = { title, completed };   const numberOfValues = Object.values(todoToUpdate).filter(Boolean).length;  if (numberOfValues === 0)  return res.status(400).json({  error: {  message: `Request body must content either 'title' or 'completed'`,  },  });  const updated = await service.update(todo_id, todoToUpdate);  res.status(200).json(serializeTodo(updated[0])); }  async function destroy(req, res) {  const { todo_id } = req.params;  await service.destroy(todo_id);  res.status(204).end(); }  async function list(req, res, next) {  const data = await service.list();  res.json({ data }); }  module.exports = {  create,  update: [idIsValid, update],  read: [idIsValid, read],  destroy: [idIsValid, destroy],  list, };  

todo.router.js файл:

 const router = require("express").Router(); const controller = require("./todo.controller");  router  .route("/")  .get(controller.list)  .post(controller.create)  router  .route("/:todo_id")  .get(controller.read)  .patch(controller.update)  .delete(controller.destroy)  module.exports = router;  

Комментарии:

1. что вы подразумеваете под правильным? У вас возникли какие-либо проблемы с запуском кода?