//Customer State Machine
const CustomerStateMachine = createMachine(
{
id: "customer",
initial: "pending",
states: {
pending: {
on: {
PASSWORD_RESET_COMPLETED: {
target: "active",
actions: ["activate"],
},
DELETE: {
target: "delete",
actions: ["delete"],
},
},
},
active: {
on: {
DEACTIVATE: {
target: "deactive",
actions: ["deactivate"],
},
DELETE: {
target: "delete",
actions: ["delete"],
},
},
},
deactive: {
on: {
ACTIVATE: {
target: "active",
actions: ["activate"],
},
DELETE: {
target: "delete",
actions: ["delete"],
},
},
},
delete: {
type: "final",
},
},
},
{
actions: {
// action implementations
activate: async (context, event) => {
await updateCustomerState(context, event, cepSTATUS.CUSTOMER.ACTIVE);
console.log("activate called....");
},
delete: async (context, event) => {
await updateCustomerState(context, event, cepSTATUS.CUSTOMER.DELETE);
console.log("delete customer called....");
},
deactivate: async (context, event) => {
console.log("deactivate customer called....");
await updateCustomerState(context, event, cepSTATUS.CUSTOMER.DEACTIVE);
console.log("deactivate customer called....");
},
},
},
);
//update customer state using this function
const updateCustomerState = (context, event, status) =>
new Promise((resolve, reject) => {
//customer id validation
if (!event.customer_id) {
return reject("Invalid customer id");
}
//update customer status here
Customer.update(
{
state: status,
},
{
where: {
customer_id: event.customer_id,
},
},
)
.then((cResult) => {
if (!cResult) {
return reject("Invalid customer");
} else {
return resolve(cResult);
}
})
.catch((err) => {
return reject("failed to update customer state");
});
});
//I have implemented this state machine for customer.
//Call Account State Machine and set account state from pending to active
const customerService = interpret(CustomerStateMachine)
.onTransition((customerState) => {
console.log(customerState.value);
})
.start();
//below line works for me
customerService.send("PASSWORD_RESET_COMPLETED", { customer_id: decodedToken.customer_id });
//but when I try below to change state of customer to deactivate customer its not working
const service = interpret(CustomerStateMachine)
.onTransition((customerState) => {
console.log(customerState.value);
})
.start();
const currentState = "active";
const nextState = CustomerStateMachine.transition(currentState, "DEACTIVATE").value;
service.send("DEACTIVATE", { customer_id: customer_id });
我有存储客户的列状态的客户表。其中 state=1 表示挂起,state=2 表示活动 state=3 表示停用,state=4 表示已删除,我必须根据操作管理数据库中的客户状态。我正在尝试使用状态机来检查当前状态下允许的操作。我做错了什么吗?请帮忙。提前致谢。