84 lines
2.1 KiB
TypeScript
84 lines
2.1 KiB
TypeScript
import { SQLDataSource } from 'datasource-sql';
|
|
import * as sql from './sql';
|
|
import {
|
|
Product,
|
|
ProductGroup,
|
|
PrintProduct,
|
|
ProductBlacklist,
|
|
} from '../types/product-types';
|
|
import { Maybe } from '../types/types';
|
|
|
|
const MINUTE = 60;
|
|
|
|
export class ProductAPI extends SQLDataSource {
|
|
constructor(config) {
|
|
super(config);
|
|
}
|
|
|
|
async getMaterial(printId: number): Promise<any> {
|
|
// SELECT materialid, material, (price / 100::float) as price FROM "product-materials"
|
|
}
|
|
|
|
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;
|
|
row.fields_json = row.fields;
|
|
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) => {
|
|
const prod = this.createProductFromRow(row);
|
|
return prod;
|
|
}),
|
|
);
|
|
return res.find(Boolean);
|
|
}
|
|
|
|
async getCategoryProducts(categoryId: number): Promise<Array<Product>> {
|
|
const query = sql.categoryProducts(categoryId);
|
|
|
|
return await this.knex
|
|
.raw(query)
|
|
.then((data) => data.rows.map((row) => this.createProductFromRow(row)));
|
|
}
|
|
}
|