Skip to content

Commit

Permalink
chore: added admin endpoint for update category
Browse files Browse the repository at this point in the history
  • Loading branch information
riqwan committed Jan 11, 2023
1 parent d8d59f6 commit bc85672
Show file tree
Hide file tree
Showing 6 changed files with 304 additions and 22 deletions.
111 changes: 91 additions & 20 deletions integration-tests/api/__tests__/admin/product-category.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ describe("/admin/product-categories", () => {
let medusaProcess
let dbConnection
let productCategory = null
let productCategory2 = null
let productCategoryChild = null
let productCategoryParent = null
let productCategoryChild2 = null
Expand All @@ -27,6 +28,7 @@ describe("/admin/product-categories", () => {
const [process, connection] = await startServerWithEnvironment({
cwd,
env: { MEDUSA_FF_PRODUCT_CATEGORIES: true },
verbose: true
})
dbConnection = connection
medusaProcess = process
Expand Down Expand Up @@ -85,26 +87,7 @@ describe("/admin/product-categories", () => {
id: productCategory.id,
name: productCategory.name,
handle: productCategory.handle,
parent_category: expect.objectContaining({
id: productCategoryParent.id,
name: productCategoryParent.name,
handle: productCategoryParent.handle,
}),
category_children: [
expect.objectContaining({
id: productCategoryChild.id,
name: productCategoryChild.name,
handle: productCategoryChild.handle,
category_children: [
expect.objectContaining({
id: productCategoryChild2.id,
name: productCategoryChild2.name,
handle: productCategoryChild2.handle,
category_children: []
})
]
})
]
parent_category_id: productCategoryParent.id
})
)

Expand Down Expand Up @@ -367,4 +350,92 @@ describe("/admin/product-categories", () => {
expect(errorFetchingDeleted.response.status).toEqual(404)
})
})

describe("POST /admin/product-categories/:id", () => {
beforeEach(async () => {
await adminSeeder(dbConnection)

productCategory = await simpleProductCategoryFactory(dbConnection, {
name: "skinny jeans",
handle: "skinny-jeans",
})

productCategory2 = await simpleProductCategoryFactory(dbConnection, {
name: "sweater",
handle: "sweater",
})
})

afterEach(async () => {
const db = useDb()
return await db.teardown()
})

it("throws an error if invalid ID is sent", async () => {
const api = useApi()

const error = await api.post(
`/admin/product-categories/not-found-id`,
{
name: 'testing'
},
adminHeaders
).catch(e => e)

expect(error.response.status).toEqual(404)
expect(error.response.data.type).toEqual("not_found")
expect(error.response.data.message).toEqual(
"ProductCategory with id: not-found-id was not found"
)
})

it("throws an error if invalid attribute is sent", async () => {
const api = useApi()

const error = await api.post(
`/admin/product-categories/${productCategory.id}`,
{
invalid_property: 'string'
},
adminHeaders
).catch(e => e)

expect(error.response.status).toEqual(400)
expect(error.response.data.type).toEqual("invalid_data")
expect(error.response.data.message).toEqual(
"property invalid_property should not exist"
)
})

it("successfully updates a product category", async () => {
const api = useApi()

const response = await api.post(
`/admin/product-categories/${productCategory.id}`,
{
name: "test",
handle: "test",
is_internal: true,
is_active: true,
parent_category_id: productCategory2.id,
},
adminHeaders
)

expect(response.status).toEqual(200)
expect(response.data).toEqual(
expect.objectContaining({
product_category: expect.objectContaining({
name: "test",
handle: "test",
is_internal: true,
is_active: true,
created_at: expect.any(String),
updated_at: expect.any(String),
parent_category_id: productCategory2.id,
}),
})
)
})
})
})
15 changes: 14 additions & 1 deletion packages/medusa/src/api/routes/admin/product-categories/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Router } from "express"

import middlewares, { transformQuery, transformBody } from "../../../middlewares"
import middlewares, {
transformQuery,
transformBody,
} from "../../../middlewares"
import { isFeatureFlagEnabled } from "../../../middlewares/feature-flag-enabled"
import deleteProductCategory from "./delete-product-category"

Expand All @@ -16,6 +19,10 @@ import createProductCategory, {
AdminPostProductCategoriesReq,
} from "./create-product-category"

import updateProductCategory, {
AdminPostProductCategoriesCategoryReq,
} from "./update-product-category"

const route = Router()

export default (app) => {
Expand Down Expand Up @@ -50,6 +57,12 @@ export default (app) => {
middlewares.wrap(getProductCategory)
)

route.post(
"/:id",
transformBody(AdminPostProductCategoriesCategoryReq),
middlewares.wrap(updateProductCategory)
)

route.delete("/:id", middlewares.wrap(deleteProductCategory))

return app
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { IsOptional, IsString } from "class-validator"
import { Request, Response } from "express"
import { EntityManager } from "typeorm"
import { ProductCategoryService } from "../../../../services"
import { AdminProductCategoriesReqBase } from "../../../../types/product-category"

/**
* @oas [post] /product-categories/{id}
* operationId: "PostProductCategoriesCategory"
* summary: "Update a Product Category"
* description: "Updates a Product Category."
* x-authenticated: true
* parameters:
* - (path) id=* {string} The ID of the Product Category.
* requestBody:
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/AdminPostProductCategoriesCategoryReq"
* x-codeSamples:
* - lang: JavaScript
* label: JS Client
* source: |
* import Medusa from "@medusajs/medusa-js"
* const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })
* // must be previously logged in or use api token
* medusa.admin.productCategories.update(categoryId, {
* name: 'Skinny Jeans'
* })
* .then(({ productCategory }) => {
* console.log(productCategory.id);
* });
* - lang: Shell
* label: cURL
* source: |
* curl --location --request POST 'https://medusa-url.com/admin/product-categories/{id}' \
* --header 'Authorization: Bearer {api_token}' \
* --header 'Content-Type: application/json' \
* --data-raw '{
* "name": "Skinny Jeans"
* }'
* security:
* - api_token: []
* - cookie_auth: []
* tags:
* - Product Category
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* type: object
* properties:
* productCategory:
* $ref: "#/components/schemas/ProductCategory"
* "400":
* $ref: "#/components/responses/400_error"
* "401":
* $ref: "#/components/responses/unauthorized"
* "404":
* $ref: "#/components/responses/not_found_error"
* "409":
* $ref: "#/components/responses/invalid_state_error"
* "422":
* $ref: "#/components/responses/invalid_request_error"
* "500":
* $ref: "#/components/responses/500_error"
*/
export default async (req: Request, res: Response) => {
const { id } = req.params
const { validatedBody } = req as {
validatedBody: AdminPostProductCategoriesCategoryReq
}

const productCategoryService: ProductCategoryService = req.scope.resolve(
"productCategoryService"
)

const manager: EntityManager = req.scope.resolve("manager")
const updated = await manager.transaction(async (transactionManager) => {
return await productCategoryService
.withTransaction(transactionManager)
.update(id, validatedBody)
})

const productCategory = await productCategoryService.retrieve(updated.id)

res.status(200).json({ product_category: productCategory })
}

/**
* @schema AdminPostProductCategoriesCategoryReq
* type: object
* properties:
* name:
* type: string
* description: The name to identify the Product Category by.
* handle:
* type: string
* description: An optional handle to be used in slugs, if none is provided we will kebab-case the name.
* metadata:
* description: An optional set of key-value pairs to hold additional information.
* type: object
*/
export class AdminPostProductCategoriesCategoryReq extends AdminProductCategoriesReqBase {
@IsString()
@IsOptional()
name?: string

@IsString()
@IsOptional()
handle?: string
}
46 changes: 46 additions & 0 deletions packages/medusa/src/services/__tests__/product-category.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,50 @@ describe("ProductCategoryService", () => {
)
})
})

describe("update", () => {
const productCategoryRepository = MockRepository({
findOne: query => {
if (query.where.id === IdMap.getId(invalidProdCategoryId)) {
return null
}

return Promise.resolve({ id: IdMap.getId(validProdCategoryId) })
},
findDescendantsTree: (productCategory) => {
return Promise.resolve(productCategory)
},
})

const productCategoryService = new ProductCategoryService({
manager: MockManager,
productCategoryRepository,
})

beforeEach(async () => {
jest.clearAllMocks()
})

it("successfully updates a product category", async () => {
await productCategoryService.update(IdMap.getId(validProdCategoryId), {
name: "bathrobes",
})

expect(productCategoryRepository.save).toHaveBeenCalledTimes(1)
expect(productCategoryRepository.save).toHaveBeenCalledWith({
id: IdMap.getId(validProdCategoryId),
name: "bathrobes",
})
})

it("fails on not-found Id product category", async () => {
const error = await productCategoryService.update(IdMap.getId(invalidProdCategoryId), {
name: "bathrobes",
}).catch(e => e)

expect(error.message).toBe(
`ProductCategory with id: ${IdMap.getId(invalidProdCategoryId)} was not found`
)
})
})
})
32 changes: 31 additions & 1 deletion packages/medusa/src/services/product-category.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { ProductCategory } from "../models"
import { ProductCategoryRepository } from "../repositories/product-category"
import { FindConfig, Selector, QuerySelector } from "../types/common"
import { buildQuery } from "../utils"
import { CreateProductCategory } from "../types/product-category"
import {
CreateProductCategory,
UpdateProductCategory,
} from "../types/product-category"

type InjectedDependencies = {
manager: EntityManager
Expand Down Expand Up @@ -116,6 +119,33 @@ class ProductCategoryService extends TransactionBaseService {
})
}

/**
* Updates a product category
* @param productCategoryId - id of product category to update
* @param productCategoryUpdate - parameters to update in product category
* @return updated product category
*/
async update(
productCategoryId: string,
productCategoryUpdate: UpdateProductCategory
): Promise<ProductCategory> {
return await this.atomicPhase_(async (manager) => {
const productCategoryRepo = manager.getCustomRepository(
this.productCategoryRepo_
)

const productCategory = await this.retrieve(productCategoryId)

for (const key in productCategoryUpdate) {
if (isDefined(productCategoryUpdate[key])) {
productCategory[key] = productCategoryUpdate[key]
}
}

return productCategoryRepo.save(productCategory)
})
}

/**
* Deletes a product category
*
Expand Down
8 changes: 8 additions & 0 deletions packages/medusa/src/types/product-category.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ export type CreateProductCategory = {
is_active?: boolean
}

export type UpdateProductCategory = {
name?: string
handle?: string
is_internal?: boolean
is_active?: boolean
parent_category_id?: string | null
}

export class AdminProductCategoriesReqBase {
@IsBoolean()
@IsOptional()
Expand Down

0 comments on commit bc85672

Please sign in to comment.