Hello! On my current project, I'm working on a password-less connection; I have a usecase class to handle connection code creation. I have a method that creates code, and it checks if there's already an existing code, if so, it replaces it with a new one. The problem is that when I send too many requests in a short time, it crashes on this method. It returns me an error: The key already exists (Because there is a constraint on my SQL table, and there can be only one code per email). And I don't want my server to crash just for that. I don't know if that's an async error. I guess I can add a middleware to limit requests but I don't know if there's a better way to fix that...
Here's my current methods, if someone think of a way to improve it, I'd like it!
async CreateCode(email: string, userId: string): Promise<Code | Error> {
const code = Math.floor((Math.random() * 899999) + 100000);
const newCode: Code = {
code: code,
email: email,
expiresAt: Date.now() + 15 * 60 * 1000,
userId: userId
}
try {
const existingCode = await this.GetCodeByEmail(email);
if (!(existingCode instanceof Error)) {
const deletionError = await this.DeleteCode(existingCode.code);
if (deletionError) {
return new ErrorWithCode(deletionError.message, 500);
}
}
await this.codeRepository.InsertOne(newCode);
return newCode;
} catch (error) {
if (error instanceof Error) {
return new ErrorWithCode(error.message, 500);
}
return Promise.resolve(null as unknown as Code);
}
}