Функция API REST Nodejs выдает ошибку «Обратный вызов не является функцией» - PullRequest
0 голосов
/ 08 октября 2019

Я пишу REST API приложения узла, используя Sqlite3. Приложение будет иметь учетные записи, и пользователь должен иметь возможность создавать и обновлять один. Мой код для создания и извлечения учетных записей работает как задумано, но моя функция обновления выдает ошибку: «TypeError: обратный вызов не является функцией»

Бэкэнд разделен на два файла;db.js - где я настраиваю базу данных и создаю базовую функцию для get / post / put / delete, и app.js - где я вызываю функцию из db и выполняю проверки правильности.

при запускефункция в почтальоне, я получаю код ошибки 500. в vscode терминал читает:

Project / 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()
        }
    })
})
...