简体   繁体   中英

I am getting updated object even though the variable has no knowledge of item update in express js

router.get("/:ticketid", async (req, res) => {
    try {
        const ticket = await ticketTable.findByPk(req.params.ticketid);

        const severityTimeSpaninMinutes = {
            "Severity 1 - Critical Business Impact": 1 * 60 * 24,
            "Severity 2 - Significant Business Impact": 3 * 60 * 24,
            "Severity 3 - Some Business Impact": 90 * 60 * 24,
            "Severity 4 - Minimal Business Impact": 91 * 60 * 24
        }

        if (ticket) {
            //  check if time until caseSubmittedDate is more than 1 day
            const timeUntilCaseSubmittedDate = dayjs(ticket.caseSubmittedDate).diff(dayjs(), 'minute')
            //  if yes, then update the ticketSLA to "Not Met"
            if (timeUntilCaseSubmittedDate < -severityTimeSpaninMinutes[ticket.priority]) {
                await ticketTable.update({
                    ticketSLA: "Not Met"
                }, {
                    where: {
                        tID: ticket.tID
                    }
                })
            }
            // get attachments based on R_TID
            const attachments = await attachmentTable.findAll({
                where: {
                    R_ID: ticket.tID,
                    columnName: "Requestor"
                }
            })

            res.json({
                data: { ...ticket.toJSON(), attachments },
                statusCode: 200,
                statusMessage: `Successfully fetched ${ticket.toJSON().ticketNo}`
            })
        } else {
            res.status(400).json({
                statusCode: 400,
                statusMessage: "Missing Ticket"
            })
        }
    } catch (err) {
        return res.status(500).json({
            statusCode: 500,
            statusMessage: err.message
        })
    }
})

here ticket stores particular item fetched from ticket table in the beginning using sequelize

And there is an update happening inside an if condition on the table.

To my surprise ticket in data: {...ticket.toJSON(), attachments }, automatically gets the updated value from the table, even though it was defined before the update.

How this works?

The variable is behaving as though it was assigned by reference instead of by value. In a lot of languages objects are automatically assigned by reference. Think of a reference like a shortcut or pointer to the real thing. Primitives are assigned by value instead behaving more like what you're used to. To assign an object by value, you must copy that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM