From 1d5d75d354907ce80b7ed0af26283b8b636246df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arwid=20Thornstr=C3=B6m?= Date: Mon, 11 Oct 2021 11:46:49 +0200 Subject: [PATCH] add unique product path function when addProduct (#67) * add unique product path function when addProduct * refactor comments --- src/datasources/product-api.ts | 40 +++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/datasources/product-api.ts b/src/datasources/product-api.ts index bbae813..3a4c506 100644 --- a/src/datasources/product-api.ts +++ b/src/datasources/product-api.ts @@ -269,12 +269,50 @@ export class ProductAPI extends BaseSQLDataSource { ); } + async getUniqueProductSlug(slug: string): Promise { + // Check for unique-slug + // Get paths from product-products + const pathResponse = await this.knex.raw( + `SELECT path FROM "product-products" WHERE path LIKE ?`, + [slug + '%'], + ); + const paths = pathResponse.rows.map((item) => item.path); + + // Evaluate new pathname + let newSlug = ''; + // If the exact match of the slug is not listed + // in the paths queried from db. Then use the + // tested slug. + if (!paths.includes(slug)) { + newSlug = slug; + } else { + // Try to find any numbers in the pathname + const numbers = paths + .map((path) => { + return parseInt(path.replace(slug + '-', '')); + }) + .filter(Boolean); // Remove falsy + if (numbers.length === 0) { + // No numbers found, add 1. + newSlug = slug + '-1'; + } else { + // Get highest number + 1 + const next = Math.max(...numbers) + 1; + newSlug = slug + '-' + next; + } + } + return newSlug; + } + async addProduct(name: string, batch: string): Promise { const path = batch ? batch + ' ' + name : name; + const productSlug = slug(path); + const safeSlug = await this.getUniqueProductSlug(productSlug); + const idres = await this.knex .table('product-products') .insert({ - path: slug(path), + path: slug(safeSlug), browsable: 0, visible: 0, })