diff --git a/src/datasources/product-api.ts b/src/datasources/product-api.ts index 988c23a..077f05c 100644 --- a/src/datasources/product-api.ts +++ b/src/datasources/product-api.ts @@ -5,6 +5,7 @@ import { ProductGroup, PrintProduct, ProductBlacklist, + Category, } from './product-types'; import { Maybe } from './types'; @@ -15,6 +16,24 @@ export class ProductAPI extends SQLDataSource { super(config); } + async getCategories(productId: number): Promise> { + 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; + } + getBlacklisting(row: any): Array { if (!row.blacklisting) { return []; diff --git a/src/datasources/product-types.ts b/src/datasources/product-types.ts index 58450de..10e8df8 100644 --- a/src/datasources/product-types.ts +++ b/src/datasources/product-types.ts @@ -8,6 +8,10 @@ export enum ProductGroup { FRAMED_PRINT = 8, } +export interface Category { + id: number; + name: string; +} export interface ProductBlacklist { id: number; groupId: number; diff --git a/src/resolvers/products-resolver.ts b/src/resolvers/products-resolver.ts index acd54e9..c4aa670 100644 --- a/src/resolvers/products-resolver.ts +++ b/src/resolvers/products-resolver.ts @@ -7,6 +7,12 @@ const ProductBlacklist: IResolverObject = { }, }; +const Product: IResolverObject = { + async categories({ id }, args, { dataSources }) { + return dataSources.productApi.getCategories(id); + }, +}; + async function getProducts(_, { limit, visible, browsable }, { dataSources }) { return dataSources.productApi.getProducts(limit, visible, browsable); } @@ -17,6 +23,7 @@ async function getProduct(_, { id }, { dataSources }) { export const productTypeDefs = { ProductBlacklist, + Product, }; export const productQueryTypeDefs = { diff --git a/src/schema.ts b/src/schema.ts index b59f69c..d4c8f2b 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -124,6 +124,7 @@ const typeDefs = gql` updated: DateTime printProducts: [PrintProduct] blacklisting: [ProductBlacklist] + categories: [Category] } enum ProductGroup { @@ -157,42 +158,18 @@ const typeDefs = gql` export { typeDefs }; /** - - -type Category { - id: ID! - name: String -} - - type Designer { id: ID! name: String orderRows(fromDate: Date, toDate: Date): [OrderRow] } -type PrintProduct { - insertedDate: DateTime! - updatedDate: DateTime -} - type Product { - categories: [Category] designer: Designer - insertedDate: DateTime! - updatedDate: DateTime -} - -type ProductBlacklist { - market: Market - insertedDate: DateTime! - updatedDate: DateTime } type Query { - product(id: Int!): Product designer(id: Int!): Designer designers: [Designer] } - */