0

我正在使用 Sqlite3 编写节点应用程序的 REST API。该应用程序将有帐户,用户应该能够创建和更新一个。我用于创建和获取帐户的代码按预期工作,但我的更新函数抛出错误:“TypeError:回调不是函数”

后端分为两个文件;db.js——我在其中设置数据库并为 get/post/put/delete 和 app.js 创建基本函数——我从 db 调用该函数并执行验证检查。

当我在邮递员中运行该函数时,我得到错误代码 500。在 vscode 中,终端读取:

项目/rbrneck/rbrneck-backend/db.js:124 回调([], updatedAccount) ^

TypeError:回调不是 Statement.db.run 中的函数

代码:

//in db.js
exports.updateAccountById = (id, updatedAccount, callback) => {

    const query = 'UPDATE accounts SET username = ?, password = ? WHERE id = ?'
    const values = [
        id,
        updatedAccount.username,
        updatedAccount.password
    ]

    db.run(query, values, (error) => {
        if(error) {
            if(error.message == "SQLITE_CONSTRAINT: UNIQUE constraint failed: accounts.username") { //username taken
                callback(['usernameTaken'])
            } else {
                callback(['databaseError'])
            }
        } else {
            //const accountUpdated = (this.changes == 1)
            callback([], updatedAccount) //HERE IS THE CALLBACK THE ERROR IS REFERRING TO
        }
    })
}

// in app.js:
app.put('/accounts/:id', (req, res, next) => {

    const id = req.params.id
    const updatedAccount = req.body

    //errors and validation
    //type of input
    if(typeof(updatedAccount.username) !== 'string' && typeof(updatedAccount.password) !== 'string') {
        res.status(422).json({
            message: 'Unprocessable Entry'
        }).end()
        return
    }

    //does the account exist?
    db.getAccountById(id, (errors, oldAccount) => {
        if(errors.length > 0) {
            res.status(500).json({
                message: 'Internal Server Error'
            }).end()
            return
        } else if (!oldAccount) {
            res.status(404).end()
            return
        }
    })

    //validation:
    const validationErrors = []
    if(updatedAccount.username.length < USERNAME_MIN_LENGTH) {
        validationErrors.push('Username too short')
    } else if (updatedAccount.username.length > USERNAME_MAX_LENGTH) {
        validationErrors.push('Username too long')
    }

    if(updatedAccount.password.length < PASSWORD_MIN_LENGTH) {
        validationErrors.push('Password too short')
    } else if (updatedAccount.password.length > PASSWORD_MAX_LENGTH) {
        validationErrors.push('Password too long')
    }

    if(validationErrors.length > 0) {
        res.status(400).json(validationErrors).end()
        return
    }

    db.updateAccountById(updatedAccount, (errors, userId) => {
        if(errors.length == 0) {
            res.setHeader('Location', '/accounts/' + userId) 
            res.status(201).end()
        } else if (errors.includes('usernameTaken')) {
            res.status(400).json(errors).end()
        } else {
            res.status(500).end()
        }
    })
})
4

0 回答 0