From 17b192fe37c14d978ae78a9537f552cf055bf5e2 Mon Sep 17 00:00:00 2001 From: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com> Date: Wed, 6 Oct 2021 11:19:38 +0200 Subject: [PATCH] fix: Throw on cart creation when no region exist (#455) If you try to create a cart without a region in your setup, we should throw a proper error message. --- integration-tests/api/__tests__/store/cart.js | 18 ++++++++++++++++++ .../src/api/routes/store/carts/create-cart.js | 8 ++++++++ 2 files changed, 26 insertions(+) diff --git a/integration-tests/api/__tests__/store/cart.js b/integration-tests/api/__tests__/store/cart.js index 034601e839..00177015de 100644 --- a/integration-tests/api/__tests__/store/cart.js +++ b/integration-tests/api/__tests__/store/cart.js @@ -63,6 +63,24 @@ describe("/store/carts", () => { expect(getRes.status).toEqual(200) }) + it("fails to create a cart when no region exist", async () => { + const api = useApi() + + await dbConnection.manager.query( + `UPDATE "country" SET region_id=null WHERE iso_2 = 'us'` + ) + await dbConnection.manager.query(`DELETE from region`) + + try { + await api.post("/store/carts") + } catch (error) { + expect(error.response.status).toEqual(400) + expect(error.response.data.message).toEqual( + "A region is required to create a cart" + ) + } + }) + it("creates a cart with country", async () => { const api = useApi() diff --git a/packages/medusa/src/api/routes/store/carts/create-cart.js b/packages/medusa/src/api/routes/store/carts/create-cart.js index 88fe6dc6ca..eb3ac34cec 100644 --- a/packages/medusa/src/api/routes/store/carts/create-cart.js +++ b/packages/medusa/src/api/routes/store/carts/create-cart.js @@ -82,6 +82,14 @@ export default async (req, res) => { if (!value.region_id) { const regionService = req.scope.resolve("regionService") const regions = await regionService.withTransaction(manager).list({}) + + if (!regions?.length) { + throw new MedusaError( + MedusaError.Types.INVALID_DATA, + `A region is required to create a cart` + ) + } + regionId = regions[0].id }