Saturday, 1 June 2019

How to generate a unique string with Express JS

I haven't written the code yet, I'm just wondering if this is an efficient way of accomplishing the task.What I'm trying to do is create a unique, hyphenated string based on product titles added to a database.For example, let's say someone adds a product "Red Shoes" to the database. I have a utility that takes that product name, and turns it into a hyphenated string like: "red-shoes"However, it doesn't stop anyone from adding another product to the database called "Red Shoes". If another "Red Shoes" product was added to the database, I'd like to create a unique hyphenated string like "red-shoes-1".I'm just not sure how this would be done. The steps I've thought of are below:User saves new productApplication generates hyphen stringApplication queries the database to see if any other entry has that hyphen stringIf no duplicates, save new product to databaseIf there is a duplicate, application appends an extra hyphen with a sequentially incremented number to the end of the stringRepeat #3My fear is that this is wildly inefficient. However, I am creating a SSR application with Next.js and need the ability to generate unique url slugs like "/product/red-shoes" and "product/red-shoes-1", but I'm not sure what the easiest way to do this is.New products won't be added often. Maybe 2 - 3 products every 2 months.

Submitted June 02, 2019 at 01:24AM by wipedingold

No comments:

Post a Comment