add unique product path function when addProduct (#67)
* add unique product path function when addProduct * refactor comments
This commit is contained in:
@@ -269,12 +269,50 @@ export class ProductAPI extends BaseSQLDataSource {
|
||||
);
|
||||
}
|
||||
|
||||
async getUniqueProductSlug(slug: string): Promise<string> {
|
||||
// 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<number> {
|
||||
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,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user