如何在Node.js

时间:2018-01-07 07:20:09

标签: javascript node.js sqlite express express-router

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

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

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

我需要做的是当sqlite数据库中不存在:id时,返回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;

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

如果rows在没有此类ID时为空对象,则!rows!{},即false。因此,它改为进入else条件。

空对象(!{})的否定为false,因为{}不是假值。唯一的假值是false0""nullundefinedNaN

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

只需将代码更改为

即可
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});
    }
  });
});