RE: How to write script to avoid duplicate record creation before record submit using suitescript 2.0
I want to create a user event script to avoid custom record creation if record is duplicate.
Also this custom record is being attached to another custom record. I have to stop from creating and attaching custom duplicate record.
One thing to be careful of, this User Event runs for both Create and Edit, but you probably only want or need to prevent a duplicate in Create mode. I’d still recommend the use of the external id just for the simplicity of it. Two ore more user events could run at nearly the same time, and there could be a race condition, where multiple UE scripts find no existing record with the two values, so they all proceed to create their records regardless. The problem is that time passes between checking for the existing record, and the eventual saving of the record. To ensure it never created duplicates, the check and save would have to be a single operation, but there is no API in SuiteScript for that. The externalid approach is the only way I know of that avoids the possibility of race conditions for this kind of scenario. It is very difficult to achieve that in SuiteScript, unless you are using a scheduled script where only one deployment can run at a time. The best you can do otherwise is to prepare the record, then do the duplicate check at the very end, to shorten the time duration before the record is saved as much as possible.
Also, the saved search in the code has no filters, which means it will take longer to run, and then even more time to loop through the results. You would instead want a search that only looked for records with the two values you want to find. Then, you just need to check if there were any results at all. For the duplicate check to be successful, the function has to be as efficient as possible, because even then there is still a race condition, but you can limit the impact of it.