diff --git a/src/datasources/product-api.ts b/src/datasources/product-api.ts index eb25911..0d848ae 100644 --- a/src/datasources/product-api.ts +++ b/src/datasources/product-api.ts @@ -536,4 +536,32 @@ export class ProductAPI extends BaseSQLDataSource { promises.push(query); return Promise.all(promises); } + + async addCategoriesToProduct( + productId, + categoryIds, + ): Promise[]> { + const promises = categoryIds.map((categoryId) => + this.knex('product_category').insert({ + product_id: productId, + category_id: categoryId, + }), + ); + return Promise.all(promises); + } + + async removeCategoriesFromProduct( + productId, + categoryIds, + ): Promise[]> { + const promises = categoryIds.map((categoryId) => + this.knex('product_category') + .where({ + product_id: productId, + category_id: categoryId, + }) + .del(), + ); + return Promise.all(promises); + } } diff --git a/src/resolvers/products-resolver.ts b/src/resolvers/products-resolver.ts index cd65f2a..89d9b8f 100644 --- a/src/resolvers/products-resolver.ts +++ b/src/resolvers/products-resolver.ts @@ -180,4 +180,24 @@ export const productMutationTypeDefs = { ); return (dataSources.productApi).getProduct(productId); }, + + async addCategoriesToProduct(_, { productId, categoryIds }, { dataSources }) { + await (dataSources.productApi).addCategoriesToProduct( + productId, + categoryIds, + ); + return (dataSources.productApi).getProduct(productId); + }, + + async removeCategoriesFromProduct( + _, + { productId, categoryIds }, + { dataSources }, + ) { + await (dataSources.productApi).removeCategoriesFromProduct( + productId, + categoryIds, + ); + return (dataSources.productApi).getProduct(productId); + }, }; diff --git a/src/schema.graphql b/src/schema.graphql index 1c58151..8161702 100644 --- a/src/schema.graphql +++ b/src/schema.graphql @@ -459,4 +459,7 @@ type Mutation { removeRelatedProducts(productId: Int!, relatedProductIds: [Int]!): Product addKeyword(name: String!, type: KeywordType): Keyword + + addCategoriesToProduct(productId: Int!, categoryIds: [Int]!): Product + removeCategoriesFromProduct(productId: Int!, categoryIds: [Int]!): Product }