0

我有一个我正在处理的 node.js API,它在 URL 中有一些参数变量。

我需要完成的任务之一是,当特定 id 无效时(如在 sqlite 数据库中不存在 id 号),它返回 404

典型的网址设置是localhost/api/employees/:id/timesheets

我需要做的是当:idsqlite 数据库中不存在它时,返回 404 但是无论我现在做什么,它都会返回 201。

请从时间表端点在下面找到我的代码,让我知道我哪里出错了,非常感谢。简而言之,假设员工 200 不存在(所以localhost/api/employees/200/timesheets- 我希望在该时间表端点上显示 404,但目前它给出了 200 而不是 404。请注意,目前没有任何方法按照要求提供 404在下面的代码中

谢谢

const express = require('express');
const timesheetsRouter = express.Router({mergeParams: true});

const sqlite3 = require('sqlite3');
const db = new sqlite3.Database(process.env.TEST_DATABASE || './database.sqlite');


timesheetsRouter.param('id', (req, res, next, id) => {
  req.id = id;
  console.log('doing name validations on ' + id);
  db.get('Select * from Timesheet where employee_id = $id', {$id: id}, (error, timesheet) => {
    if (error) {
      next(error);
    } else if (timesheet) {
      req.timesheet = timesheet;
      next();
    } else {
      res.sendStatus(404);
    }
  });
});

timesheetsRouter.get('/', (req, res, next) => {
  db.all(`select * from Timesheet where employee_id = $id`, {$id: req.params.id}, (error, rows) => {
      //console.log('executed sql');
      //console.log(rows);
    if (!rows) {
      console.log('triggered');
        //console.log('this is error ' + error);
        res.sendStatus(404);
      //next();
    } else {
      console.log(rows + ' This is rows');
      res.status(200).json({timesheets: rows});
    }
  });
});


const validateTimesheet = (req, res, next) => {
    //console.log('this is menu ' + req.body);
  if (!req.body.timesheet.hours || !req.body.timesheet.rate || !req.body.timesheet.date) {
    return res.sendStatus(400);
  }
  next();
}



  timesheetsRouter.post('/', validateTimesheet, (req, res, next) => {    
    //console.log('this is mmenu post body ' + req.body.menu.title);
    db.run(`INSERT INTO Timesheet(hours, rate, date, employee_id) VALUES ($hours, $rate, $date, $employee_id)`, 
    { $hours: req.body.timesheet.hours, $rate: req.body.timesheet.rate, $date: req.body.timesheet.date, $employee_id:req.params.id}, function (error) {
        if (error) {
            ('error with sql  ' + console.log(error));
            return res.sendStatus(500);
        }   

        db.get(`SELECT * FROM Timesheet WHERE id = ${this.lastID}`, (err, row) => {
      if (err) {
          //console.log(err);
        return res.sendStatus(500);
      } else {
       res.status(201).json({timesheet: row});
      }
  });
    })
})

timesheetsRouter.put('/:id', validateTimesheet, (req, res, next) => {

    const timesheetToUpdate = req.body.employee;
    //console.log(artistToUpdate);
    //console.log("this is params " + req.params.id);
    db.run(`UPDATE Timesheet SET hours=$hours, rate=$rate, date=$date where id=${req.params.id}`,
    {$hours:req.body.timesheet.hours, $rate: req.body.timesheet.rate, $date:req.body.timesheet.date}), function (error, row) {
        console.log(row);
        if (error) {
            console.log('this is error ' + error);
            return res.status(404).send();
        }
    }
        db.get(`SELECT * from Timesheet where id = $id`, {$id: req.params.id}, (error, row) => {
            if(!row) {
                return res.sendStatus(500);
            }
            //console.log(row);
            res.status(200).send({timesheet: row});
        })

    });




module.exports = timesheetsRouter;
4

2 回答 2

0

在终端中运行它npm install lodash --save。Lodash 是一个非常漂亮的实用程序,可以在任何项目中使用

我曾经_.isEmpty()检查您是否已收到数据,然后相应地进行处理。您可以在此处查看详细信息https://lodash.com/docs/#isEmpty

const express = require('express');
const timesheetsRouter = express.Router({mergeParams: true});

const sqlite3 = require('sqlite3');
const _ = require('lodash');
const db = new sqlite3.Database(process.env.TEST_DATABASE || './database.sqlite');


timesheetsRouter.param('id', (req, res, next, id) => {
  req.id = id;
  console.log('doing name validations on ' + id);
  db.get('Select * from Timesheet where employee_id = $id', {$id: id}, (error, timesheet) => {
    if (error) {
      next(error);
    } else if (!_.isEmpty(timesheet)) {
      req.timesheet = timesheet;
      next();
    } else {
      res.sendStatus(404);
    }
  });
});

timesheetsRouter.get('/', (req, res, next) => {
  db.all(`select * from Timesheet where employee_id = $id`, {$id: req.params.id}, (error, rows) => {
      //console.log('executed sql');
      //console.log(rows);
    if (!rows) {
      console.log('triggered');
        //console.log('this is error ' + error);
        res.sendStatus(404);
      //next();
    } else {
      console.log(rows + ' This is rows');
      res.status(200).json({timesheets: rows});
    }
  });
});


const validateTimesheet = (req, res, next) => {
    //console.log('this is menu ' + req.body);
  if (!req.body.timesheet.hours || !req.body.timesheet.rate || !req.body.timesheet.date) {
    return res.sendStatus(400);
  }
  next();
}



  timesheetsRouter.post('/', validateTimesheet, (req, res, next) => {    
    //console.log('this is mmenu post body ' + req.body.menu.title);
    db.run(`INSERT INTO Timesheet(hours, rate, date, employee_id) VALUES ($hours, $rate, $date, $employee_id)`, 
    { $hours: req.body.timesheet.hours, $rate: req.body.timesheet.rate, $date: req.body.timesheet.date, $employee_id:req.params.id}, function (error) {
        if (error) {
            ('error with sql  ' + console.log(error));
            return res.sendStatus(500);
        }   

        db.get(`SELECT * FROM Timesheet WHERE id = ${this.lastID}`, (err, row) => {
      if (err) {
          //console.log(err);
        return res.sendStatus(500);
      } else {
       res.status(201).json({timesheet: row});
      }
  });
    })
})

timesheetsRouter.put('/:id', validateTimesheet, (req, res, next) => {

    const timesheetToUpdate = req.body.employee;
    //console.log(artistToUpdate);
    //console.log("this is params " + req.params.id);
    db.run(`UPDATE Timesheet SET hours=$hours, rate=$rate, date=$date where id=${req.params.id}`,
    {$hours:req.body.timesheet.hours, $rate: req.body.timesheet.rate, $date:req.body.timesheet.date}), function (error, row) {
        console.log(row);
        if (error) {
            console.log('this is error ' + error);
            return res.status(404).send();
        }
    }
        db.get(`SELECT * from Timesheet where id = $id`, {$id: req.params.id}, (error, row) => {
            if(!row) {
                return res.sendStatus(500);
            }
            //console.log(row);
            res.status(200).send({timesheet: row});
        })

    });




module.exports = timesheetsRouter;
于 2018-01-07T07:39:43.990 回答
0

如果rows没有这样的 id 时是一个空对象,那么!rowsis !{}which is falseelse因此,它改为进入条件。

对空对象 ( !{}) 的否定是falseas {}is not a falsy value。唯一的虚假值是false, 0, "", null, undefined, 和NaN

检查对象是否为空的一种简单方法是Object.keys({}).length === 0. 无需安装 Lodash 即可使用_.isEmpty.

只需将您的代码更改为

timesheetsRouter.get('/', (req, res, next) => {
  db.all(`select * from Timesheet where employee_id = $id`, {$id: req.params.id}, (error, rows) => {
    if (Object.keys(rows).length === 0) {
      res.sendStatus(404);
    } else {
      console.log(rows + ' This is rows');
      res.status(200).json({timesheets: rows});
    }
  });
});
于 2018-01-07T07:45:11.573 回答