Add keywords and product types

This commit is contained in:
Niklas Fondberg
2021-07-07 16:16:58 +02:00
parent 512ebf89f5
commit 267bc4f1c9
11 changed files with 262 additions and 53 deletions
+75
View File
@@ -0,0 +1,75 @@
import { SQLDataSource } from 'datasource-sql';
import { Keyword, KeywordType } from '../types/keyword-types';
const MINUTE = 60;
export class KeywordAPI extends SQLDataSource {
constructor(config) {
super(config);
}
getType(data: any) {
// raw queries doesn't camelCase...
const typeObject = data.type_id ?? data.typeId;
const typeId = typeObject ?? 0;
return {
...data,
type: KeywordType[typeId],
};
}
async getProductKeywords(productId: number): Promise<Array<Keyword>> {
const query = /* sql */ `
SELECT keywords.*, keyword_type.type_id FROM keywords
LEFT JOIN keyword_type ON keyword_type.keyword_id = keywords.id
JOIN product_keyword ON product_keyword.keyword_id = keywords.id
WHERE product_keyword.product_id = ?
ORDER BY keywords.value
`;
const res = await this.knex
.raw(query, productId)
.then((data) => data.rows.map((row) => this.getType(row)));
return res;
}
async getKeywords(): Promise<Array<Keyword>> {
const query = /* sql */ `
SELECT keywords.*, keyword_type.type_id FROM keywords
LEFT JOIN keyword_type ON keyword_type.keyword_id = keywords.id
ORDER BY keywords.value
`;
const res = await this.knex
.raw(query)
.then((data) => data.rows.map((row) => this.getType(row)));
return res;
}
async getKeywordById(id: number): Promise<Keyword> {
const res = await this.knex
.select('*')
.from('keywords')
.leftJoin('keyword_type', 'keyword_type.keyword_id', 'keywords.id')
.where('id', id)
.first()
.cache(MINUTE)
.then((row) => this.getType(row));
return res;
}
/**
* 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
*
*/
}