【发布时间】:2021-08-25 02:12:24
【问题描述】:
我正在创建一个收藏按钮,当用户喜欢一个食谱时,我想保存用户 ID 和他喜欢的食谱的 ID。我正在使用 knex.js 并且对它仍然很陌生,除了获取用户 ID 和配方的部分之外,每个代码都可以工作。
保存配方的代码:
const { existsOrError } = app.api.validation
const save = (req, res) => {
const recipe = { ...req.body }
if (req.params.id) recipe.id = req.params.id
try {
existsOrError(recipe.name, 'Name not informed')
existsOrError(recipe.Ingredients, 'Ingredients not informed')
existsOrError(recipe.time, 'Preparation time not informed')
existsOrError(recipe.portion, 'portion not informed')
existsOrError(recipe.preparation, 'Preparation not informed')
} catch (msg) {
res.status(400).send(msg)
}
if (recipe.id) {
app.db('recipes')
.update(recipe)
.where({ id: recipe.id })
.then(_ => res.status(204).send())
.catch(err => res.status(500).send(err))
} else {
app.db('recipes')
.insert(recipe)
.then(_ => res.status(204).send())
.catch(err => res.status(500).send(err))
}
}
保存用户的代码:
const { existsOrError, notExistsOrError, equalsOrError } = app.api.validation
const encryptPassword = password => {
const salt = bcrypt.genSaltSync(10)
return bcrypt.hashSync(password, salt)
}
const save = async (req, res) => {
const user = { ...req.body }
if (req.params.id) user.id = req.params.id
if (!req.originalUrl.startsWith('/users')) user.admin = false
if (!req.user || !req.user.admin) user.admin = false
try {
existsOrError(user.name, 'Name not informed')
existsOrError(user.email, 'Email not informed')
existsOrError(user.birth, 'Date of birth not informed')
existsOrError(user.password, 'Password not entered')
existsOrError(user.confirmPassword, 'Invalid Password Confirmation')
equalsOrError(user.password, user.confirmPassword,
'Passwords do not match')
const userFromDB = await app.db('users')
.where({ email: user.email }).first()
if (!user.id) {
notExistsOrError(userFromDB, 'User already registered')
}
} catch (msg) {
return res.status(400).send(msg)
}
user.password = encryptPassword(user.password)
delete user.confirmPassword
if (user.id) {
app.db('users')
.update(user)
.where({ id: user.id })
.whereNull('deletedAt')
.then(_ => res.status(204).send())
.catch(err => res.status(500).send(err))
} else {
app.db('users')
.insert(user)
.then(_ => res.status(204).send())
.catch(err => res.status(500).send(err))
}
}
我尝试获取 id:
const save = (req, res) => {
const like = {
id: req.body.id,
userId: user.id,
recipeId: recipe.id
}
app.db('likes')
.insert(like)
.then(_ => res.status(204).send())
.catch(err => res.status(500).send(err))
}
return { save }
}
【问题讨论】:
标签: javascript node.js postgresql knex.js