Optimize SQL transactions in API
P粉343408929
2023-08-18 13:24:59
<p>I had a job interview recently and I got a little homework. Then I received feedback that I had an unnecessary combination of queries and transactions in my update endpoint. </p>
<pre class="brush:php;toolbar:false;">export const update = async (req: Request, res: Response, next: NextFunction) => {
try {
const reportId = parseInt(req.params.id)
const { name, age, info } = req.body
const report = await ReportModel.findOne({
where: {
id: reportId
}
})
if (!report) return next(new EntityNotExistError("Report does not exist"))
await ReportModel.update({
name,
age,
info
}, {
where: {
id: reportId
}
})
const _report = await ReportModel.findOne({
where: {
id: reportId
}
})
return res.json({
message: "Report edited successfully",
report: _report
})
} catch (error) {
return next(error)
}
}</pre>
<p>As you can see, the first query checks if the entity exists, then I perform an update on the entity, and the last query returns the updated entity.
Is there some way to optimize communication with the database? </p>
Your code involves three different interactions with the database for a single update operation:
ReportModel.findOne()
ReportModel.update()
ReportModel.findOne()
Reducing database queries gets the job done and improves performance.
**Your fixed code:**