I'm currently creating some API with Zeit Now, and I was trying to implement 404 error when the user
variable is []
(an empty array), but when I fetch this endpoint, API is sending []
aswell. How can I implement it? Is it because the user
is a promise?
const db = require('../../lib/db')
const escape = require('sql-template-strings')
module.exports = async (req, res) => {
const user = await db.query(escape`
SELECT *
FROM users
WHERE username = ${req.body.username}
AND password = ${req.body.password}
`)
if (user === []) {
res.status(404).json({ message: 'User with these credentials doesn\'t exist.' })
return false
}
res.status(200).json(user)
}
Because
[] === [] // false
So you want to check the length
property
if (user.length === 0) {
res.status(404).json({ message: 'User with these credentials doesn\'t exist.' })
return false
}