I am trying to implement custom validation when creating a new Customer. The logic should work as follows: if there already exists a Customer with the same combination of PhoneNumber and OperatorId, Customer should not be created and a validation message should be returned. The following code does not work as I expect.
Backendless.ServerCode.Persistence.beforeCreate('Customer', function(req) {
var inputStr = `PhoneNumber = '${req.item.PhoneNumber}' and OperatorId.objectId = '${req.item.OperatorId.objectId}'`;
var customerStorage = Backendless.Persistence.of('Customer');
function findCustomer() {
var query = {
condition: inputStr
};
return new Promise((resolve, reject) => {
customerStorage.find(query, new Backendless.Async(result => {
if (result.data.length > 0) {
reject(new Error(`Customer already exists: ${inputStr}`));
}
resolve(result.data);
}, reject));
});
}
return findCustomer()
.catch(er => Promise.reject(er));
});
When I try to save a duplicate user, I get a proper error:
{
"code": 0,
"message": "Customer already exists: PhoneNumber = '+38067 444 44 44' and OperatorId.objectId = '51CC4050-8686-2C67-FF6B-644499006000'"
}
However, when I try to create a unique Customer I get an “Internal server error with id” or “Server temporarily unavailable” in a toaster, and in debug window I see that beforeCreate event handler was called three times.
What is wrong with my code?