98 lines
2.4 KiB
TypeScript
98 lines
2.4 KiB
TypeScript
import { SQLDataSource } from 'datasource-sql';
|
|
import * as sql from './sql';
|
|
import {
|
|
Product,
|
|
ProductGroup,
|
|
PrintProduct,
|
|
ProductBlacklist,
|
|
Category,
|
|
} from './product-types';
|
|
import { Maybe } from './types';
|
|
|
|
const MINUTE = 60;
|
|
|
|
export class ProductAPI extends SQLDataSource {
|
|
constructor(config) {
|
|
super(config);
|
|
}
|
|
|
|
async getCategories(productId: number): Promise<Array<Category>> {
|
|
const query = /* sql */ `
|
|
SELECT product_category.category_id, categories.name
|
|
FROM product_category JOIN 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((o) => {
|
|
return {
|
|
...o,
|
|
id: o.category_id,
|
|
};
|
|
}),
|
|
);
|
|
return res;
|
|
}
|
|
|
|
async getMaterial(printId: number): Promise<any> {
|
|
// SELECT materialid, material, (price / 100::float) as price FROM "product-materials"
|
|
}
|
|
|
|
// TODO: get product details
|
|
async getProductDetails(id: number): Promise<any> {
|
|
// SELECT * FROM "product-fields";
|
|
// SELECT * FROM "product-products_fields" WHERE productid = 58941;
|
|
return null;
|
|
}
|
|
|
|
getBlacklisting(row: any): Array<ProductBlacklist> {
|
|
if (!row.blacklisting) {
|
|
return [];
|
|
}
|
|
return row.blacklisting.map((bl: any) => {
|
|
bl.group = ProductGroup[bl.groupId];
|
|
return bl;
|
|
});
|
|
}
|
|
|
|
getPrintProducts(row: any): Array<PrintProduct> {
|
|
if (!row.printproducts) {
|
|
return [];
|
|
}
|
|
return row.printproducts.map((pp: any) => {
|
|
pp.group = ProductGroup[pp.groupId];
|
|
pp.id = pp.printId;
|
|
return pp;
|
|
});
|
|
}
|
|
|
|
createProductFromRow(row: any) {
|
|
row.blacklisting = this.getBlacklisting(row);
|
|
row.printProducts = this.getPrintProducts(row);
|
|
row.designerId = row.designerid;
|
|
return row;
|
|
}
|
|
|
|
async getProducts(
|
|
limit: Maybe<number>,
|
|
visible: Maybe<boolean>,
|
|
browsable: Maybe<boolean>,
|
|
): Promise<Array<Product>> {
|
|
limit = limit ?? 100;
|
|
const query = sql.products(limit, visible, browsable);
|
|
|
|
return await this.knex
|
|
.raw(query)
|
|
.then((data) => data.rows.map((row) => this.createProductFromRow(row)));
|
|
}
|
|
|
|
async getProduct(id: number): Promise<Maybe<Product>> {
|
|
const query = sql.product(id);
|
|
|
|
const res = await this.knex
|
|
.raw(query)
|
|
.then((data) => data.rows.map((row) => this.createProductFromRow(row)));
|
|
return res.find(Boolean);
|
|
}
|
|
}
|