我有一个项目,其中有两个主表:Contact和Worker
我还有一个名为WorkerContact的连接表
在我的项目中,我为用户提供了删除联系人的选项,这也需要删除联接表的元素.我担心的是,在我当前的设置中(见下文),如果我遇到一个错误,我成功删除了一个联系人,但随后又未能删除相关的连接表(由于错误),那么一切都会被打乱.所以我的问题是,有没有一种方法可以重构这一点,以确保在执行实际删除之前完成这两项操作,然后将promise 发送到前端?
以下是我目前的情况:
前端:
export const destroyContact = (contact_id) => dispatch => {
axios.post(`http://localhost:3001/contacts/destroy`, {id: contact_id})
.then(() => {
dispatch({type: 'CONTACT_DESTROYED', payload: contact_id});
axios.post(`http://localhost:3001/workerContacts/destroy`, {id: contact_id}) //I'm scared that the first thing will run but the second one won't, causing a lot of problems. We can deal with this by just throwing a big error message for the user hopefully
.then(() => {
dispatch({type: 'JOIN_TABLE_ROWS_DESTROYED', payload: contact_id});
})
.catch(err => dispatch({type: 'ERROR_CAUGHT', payload: {err_message: err.response.data.message, err_code: err.response.request.status, err_value: err.response.request.statusText}}))
})
.catch(err => dispatch({type: 'ERROR_CAUGHT', payload: {err_message: err.response.data.message, err_code: err.response.request.status, err_value: err.response.request.statusText}}))
}
我也在使用redux,所以这就是为什么我有所有的dispatch等等,但本质上我已经将删除拆分为两个axios调用:一个是我删除联系人,另一个是删除连接表.
后端:
对于联系人,我有以下内容:
export const destroy = (req, res) => {
// Here is when we want to remove an existing contact
Contact.deleteMe(req.body.id)
.then(() => res.json("Contact deleted"))
.catch((err) => res.status(500).json({message: "Something went wrong when trying to save delete this. Try and reload the page and try again "}))
}
和关联的DeleteMe函数:
static deleteMe(customer_id){
//Uses SQL to delete an individual customer element
return db.execute('DELETE FROM contacts WHERE id = ?', [customer_id]);
}
对于可接合的桌子,我有这样的 idea :
export const destroy = (req, res) => {
// Here is when we want to remove an existing contact
JoinTable.deleteMe(req.body.id)
.then(() => res.json("Join tables deleted"))
.catch(err => res.status(500).json({message: "Something went wrong on our end. Try to reload the page and start again"}))
}
和关联的DeleteMe函数:
static deleteMe(customer_id){
//Uses SQL to delete an individual customer element
return db.execute('DELETE FROM workercontacts WHERE workerContacts.contact_id = ?', [customer_id]);
}
如果有帮助的话,我正在使用MySQL数据库.
希望这是足够的信息,但如果您需要更多,我肯定可以提供给您.