76 lines
1.6 KiB
TypeScript
76 lines
1.6 KiB
TypeScript
import { SQLDataSource } from 'datasource-sql';
|
|
import { Category } from '../types/category-types';
|
|
|
|
const MINUTE = 60;
|
|
|
|
export class CategoryAPI extends SQLDataSource {
|
|
constructor(config) {
|
|
super(config);
|
|
}
|
|
|
|
async getProductCategories(productId: number): Promise<Array<Category>> {
|
|
const query = /* sql */ `
|
|
SELECT product_category.category_id as id,
|
|
categories.*
|
|
FROM product_category
|
|
JOIN v_categorytree categories ON product_category.category_id = categories.id
|
|
WHERE product_category.product_id = ?
|
|
`;
|
|
|
|
const res = await this.knex.raw(query, productId).then((data) =>
|
|
data.rows.map((row) => {
|
|
return {
|
|
...row,
|
|
path: row.path.replace(/^root/, ''),
|
|
};
|
|
}),
|
|
);
|
|
return res;
|
|
}
|
|
|
|
async getCategories(): Promise<Array<Category>> {
|
|
return await this.knex
|
|
.select('*')
|
|
.from('v_categorytree')
|
|
.cache(MINUTE)
|
|
.then((rows) => {
|
|
return rows.map((row) => {
|
|
return {
|
|
...row,
|
|
path: row.path.replace(/^root/, ''),
|
|
};
|
|
});
|
|
});
|
|
}
|
|
|
|
async getCategoryById(id: number): Promise<Category> {
|
|
return await this.knex
|
|
.select('*')
|
|
.from('v_categorytree')
|
|
.where('id', id)
|
|
.first()
|
|
.cache(MINUTE)
|
|
.then((row) => {
|
|
return {
|
|
...row,
|
|
path: row.path.replace(/^root/, ''),
|
|
};
|
|
});
|
|
}
|
|
|
|
/**
|
|
* category keywords
|
|
*
|
|
SELECT category_keyword.category_id, keywords.value
|
|
FROM category_keyword
|
|
JOIN keywords ON category_keyword.keyword_id = keywords.id;
|
|
|
|
|
|
FROM categorydata cd
|
|
JOIN categorydatakeys cdk ON cd.datakey_id = cdk.id
|
|
|
|
|
|
*
|
|
*/
|
|
}
|