chore: merge release

This commit is contained in:
Sebastian Rindom
2021-11-20 15:59:31 +01:00
565 changed files with 38806 additions and 16346 deletions
+21 -18
View File
@@ -1,26 +1,10 @@
# FILES TODO
/packages/medusa/src/services/cart.js
/packages/medusa/src/services/claim-item.js
/packages/medusa/src/services/event-bus.js
/packages/medusa/src/services/fulfillment-provider.js
/packages/medusa/src/services/inventory.js
/packages/medusa/src/services/middleware.js
/packages/medusa/src/services/oauth.js
/packages/medusa/src/services/payment-provider.js
/packages/medusa/src/services/product-collection.js
/packages/medusa/src/services/product-variant.js
/packages/medusa/src/services/product.js
/packages/medusa/src/services/return.js
/packages/medusa/src/services/shipping-profile.js
/packages/medusa/src/services/store.js
/packages/medusa/src/services/swap.js
/packages/medusa/src/services/totals.js
/packages/medusa/src/subscribers/notification.js
/packages/medusa/src/subscribers/order.js
/packages/medusa/src/subscribers/product.js
/packages/medusa/src/loaders/api.js
/packages/medusa/src/loaders/database.js
/packages/medusa/src/loaders/defaults.js
@@ -34,17 +18,36 @@
/packages/medusa/src/loaders/repositories.js
/packages/medusa/src/loaders/services.js
/packages/medusa/src/loaders/subscribers.js
/packages/medusa/src/api/routes/admin/auth
/packages/medusa/src/api/routes/admin/collections
/packages/medusa/src/api/routes/store/carts
/packages/medusa/src/api/routes/store/return-reasons
/packages/medusa/src/api/routes/store/returns
# JS Client
/packages/medusa-js/src/resources/auth.ts
/packages/medusa-js/src/resources/gift-cards.ts
/packages/medusa-js/src/resources/line-items.ts
/packages/medusa-js/src/resources/payment-methods.ts
/packages/medusa-js/src/resources/product-variants.ts
/packages/medusa-js/src/resources/regions.ts
/packages/medusa-js/src/resources/return-reasons.ts
/packages/medusa-js/src/resources/returns.ts
/packages/medusa-js/src/resources/shipping-options.ts
/packages/medusa-js/src/resources/swaps.ts
/packages/medusa-js/src/resources/collections.ts
/packages/medusa-js/src/types/
/packages/medusa-js/src/error.ts
# END OF FILES TODO
/packages/medusa/src/api
/packages/medusa/src/models
/packages/medusa/src/repositories
/packages/medusa/src/commands
/packages/medusa/src/helpers
/packages/medusa/src/migrations
/packages/medusa/src/utils
/integration-tests
/docs
/docs-util
+20
View File
@@ -16,18 +16,38 @@ module.exports = {
semi: `off`,
"no-unused-expressions": `off`,
camelcase: `off`,
"no-invalid-this": `off`,
},
env: {
es6: true,
node: true,
jest: true,
},
ignorePatterns: [`**/models`, `**/repositories`],
overrides: [
{
files: [`*.ts`],
parser: `@typescript-eslint/parser`,
plugins: [`@typescript-eslint/eslint-plugin`],
extends: [`plugin:@typescript-eslint/recommended`],
rules: {
"@typescript-eslint/explicit-function-return-type": ["error"],
"@typescript-eslint/no-non-null-assertion": ["off"],
},
},
{
files: ["**/api/**/*.js", "**/api/**/*.ts"],
rules: {
"valid-jsdoc": ["off"],
},
},
{
files: ["**/api/**/*.ts"],
rules: {
"valid-jsdoc": ["off"],
"@typescript-eslint/explicit-function-return-type": ["off"],
"@typescript-eslint/no-var-requires": ["off"],
},
},
],
}
@@ -0,0 +1,33 @@
name: cache-bootstrap
description: Creates a cache with the given extension for lerna packages
inputs:
extension:
description: Extension for cache name
partial:
description: Boolean flag to describe whether or not to run a partial bootstrap when finding cache
default: false
runs:
using: composite
steps:
# for always overriding cache, use: pat-s/always-upload-cache@v2.1.5
- uses: actions/cache@v2
id: cache
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-yarn-${{inputs.extension}}-v8-${{ hashFiles('**/yarn.lock') }}
# We want to only bootstrap and install if no cache is found.
# Futhermore, we might want to do a partial, hoisted, bootstrap towards
# the base branch if it exists, otherwise we choose develop for this.
# yarn install --frozen-lockfile
- run: |
if [[ "${{steps.cache.outputs.cache-hit}}" != "true" || "${{inputs.partial}}" != "true" ]]; then
yarn install --frozen-lockfile
yarn bootstrap --concurrency=2
elif [[ "${{inputs.partial}}" = "true" ]]; then
[[ ! -z "${GITHUB_BASE_REF}" ]] && ref="${GITHUB_BASE_REF#refs/heads/}" || ref="develop"
yarn bootstrap --npm-client=npm --hoist --since "origin/${ref}...HEAD" --concurrency=2
fi
shell: bash
+92
View File
@@ -0,0 +1,92 @@
name: Medusa Pipeline
on: [push, pull_request]
jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.9.1
with:
access_token: ${{ github.token }}
- name: Checkout
uses: actions/checkout@v2.3.5
with:
fetch-depth: 0
- name: Setup Node.js environment
uses: actions/setup-node@v2.4.1
with:
node-version: "14"
cache: "yarn"
- name: Assert changed
run: ./scripts/assert-changed-files-actions.sh "packages"
- name: Bootstrap packages
uses: ./.github/actions/cache-bootstrap
with:
extension: unit-tests
- name: Run unit tests
run: node --max-old-space-size=2048 ./node_modules/.bin/jest -w 1
integration-tests:
runs-on: ubuntu-latest
services:
postgres:
image: postgres
env:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.9.1
with:
access_token: ${{ github.token }}
- name: Checkout
uses: actions/checkout@v2.3.5
with:
fetch-depth: 0
- name: Setup Node.js environment
uses: actions/setup-node@v2.4.1
with:
node-version: "14"
cache: "yarn"
- name: Bootstrap packages
uses: ./.github/actions/cache-bootstrap
with:
extension: integration-tests
- name: Install dev cli
run: sudo npm i -g medusa-dev-cli
- name: Set path to medusa repo
run: medusa-dev --set-path-to-repo `pwd`
- name: Force install
run: medusa-dev --force-install
working-directory: integration-tests/api
- name: Build integration tests
run: yarn build
working-directory: integration-tests/api
- name: Run integration tests
run: yarn test
working-directory: integration-tests/api
env:
DB_PASSWORD: postgres
+1 -1
View File
@@ -1,5 +1,5 @@
{
"endOfLine": "lf",
"endOfLine": "auto",
"semi": false,
"singleQuote": false,
"tabWidth": 2,
+1462 -793
View File
File diff suppressed because it is too large Load Diff
+901 -450
View File
File diff suppressed because it is too large Load Diff
+629 -526
View File
File diff suppressed because it is too large Load Diff
+677 -595
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,204 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`/admin/collections /admin/collections creates a collection 1`] = `
Object {
"collection": Object {
"created_at": Any<String>,
"deleted_at": null,
"handle": "test-handle-creation",
"id": StringMatching /\\^pcol_\\*/,
"metadata": null,
"title": "test collection creation",
"updated_at": Any<String>,
},
}
`;
exports[`/admin/collections /admin/collections lists collections 1`] = `
Object {
"collections": Array [
Object {
"handle": "test-collection",
"id": "test-collection",
"products": Array [
Object {
"collection_id": "test-collection",
"created_at": Any<String>,
"deleted_at": null,
"description": "test-product-description",
"discountable": true,
"handle": "test-product",
"height": null,
"hs_code": null,
"id": "test-product",
"is_giftcard": false,
"length": null,
"material": null,
"metadata": null,
"mid_code": null,
"origin_country": null,
"profile_id": StringMatching /\\^sp_\\*/,
"status": "draft",
"subtitle": null,
"thumbnail": null,
"title": "Test product",
"type_id": "test-type",
"updated_at": Any<String>,
"weight": null,
"width": null,
},
Object {
"collection_id": "test-collection",
"created_at": Any<String>,
"deleted_at": null,
"description": "test-product-description1",
"discountable": true,
"handle": "test-product1",
"height": null,
"hs_code": null,
"id": "test-product1",
"is_giftcard": false,
"length": null,
"material": null,
"metadata": null,
"mid_code": null,
"origin_country": null,
"profile_id": StringMatching /\\^sp_\\*/,
"status": "draft",
"subtitle": null,
"thumbnail": null,
"title": "Test product1",
"type_id": "test-type",
"updated_at": Any<String>,
"weight": null,
"width": null,
},
],
"title": "Test collection",
},
Object {
"handle": "test-collection1",
"id": "test-collection1",
"products": Array [
Object {
"collection_id": "test-collection1",
"created_at": Any<String>,
"deleted_at": null,
"description": "test-product-description",
"discountable": true,
"handle": "test-product_filtering_1",
"height": null,
"hs_code": null,
"id": "test-product_filtering_1",
"is_giftcard": false,
"length": null,
"material": null,
"metadata": null,
"mid_code": null,
"origin_country": null,
"profile_id": StringMatching /\\^sp_\\*/,
"status": "proposed",
"subtitle": null,
"thumbnail": null,
"title": "Test product filtering 1",
"type_id": "test-type",
"updated_at": Any<String>,
"weight": null,
"width": null,
},
Object {
"collection_id": "test-collection1",
"created_at": Any<String>,
"deleted_at": null,
"description": "test-product-description",
"discountable": true,
"handle": "test-product_filtering_3",
"height": null,
"hs_code": null,
"id": "test-product_filtering_3",
"is_giftcard": false,
"length": null,
"material": null,
"metadata": null,
"mid_code": null,
"origin_country": null,
"profile_id": StringMatching /\\^sp_\\*/,
"status": "draft",
"subtitle": null,
"thumbnail": null,
"title": "Test product filtering 3",
"type_id": "test-type",
"updated_at": Any<String>,
"weight": null,
"width": null,
},
],
"title": "Test collection 1",
},
Object {
"handle": "test-collection2",
"id": "test-collection2",
"products": Array [
Object {
"collection_id": "test-collection2",
"created_at": Any<String>,
"deleted_at": null,
"description": "test-product-description",
"discountable": true,
"handle": "test-product_filtering_2",
"height": null,
"hs_code": null,
"id": "test-product_filtering_2",
"is_giftcard": false,
"length": null,
"material": null,
"metadata": null,
"mid_code": null,
"origin_country": null,
"profile_id": StringMatching /\\^sp_\\*/,
"status": "published",
"subtitle": null,
"thumbnail": null,
"title": "Test product filtering 2",
"type_id": "test-type",
"updated_at": Any<String>,
"weight": null,
"width": null,
},
],
"title": "Test collection 2",
},
],
"count": 3,
"limit": 10,
"offset": 0,
}
`;
exports[`/admin/collections /admin/collections/:id gets collection 1`] = `
Object {
"collection": Object {
"created_at": Any<String>,
"deleted_at": null,
"handle": "test-collection",
"id": "test-collection",
"metadata": null,
"title": "Test collection",
"updated_at": Any<String>,
},
}
`;
exports[`/admin/collections /admin/collections/:id updates a collection 1`] = `
Object {
"collection": Object {
"created_at": Any<String>,
"deleted_at": null,
"handle": "test-handle-creation",
"id": StringMatching /\\^pcol_\\*/,
"metadata": null,
"title": "test collection creation",
"updated_at": Any<String>,
},
}
`;
@@ -0,0 +1,22 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`/admin/orders POST /admin/orders/:id updates a shipping adress 1`] = `
Object {
"address_1": "Some Street",
"address_2": "",
"city": "losangeles",
"company": null,
"country_code": "us",
"created_at": Any<String>,
"customer_id": null,
"deleted_at": null,
"first_name": "lebron",
"id": Any<String>,
"last_name": null,
"metadata": null,
"phone": null,
"postal_code": "1235",
"province": "",
"updated_at": Any<String>,
}
`;
@@ -479,7 +479,7 @@ Array [
]
`;
exports[`/admin/products GET /admin/products returns a list of products with giftcard in list 1`] = `
exports[`/admin/products GET /admin/products returns a list of products with only giftcard in list 1`] = `
Array [
Object {
"collection": null,
@@ -0,0 +1,220 @@
const path = require("path")
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const productSeeder = require("../../helpers/product-seeder")
const adminSeeder = require("../../helpers/admin-seeder")
jest.setTimeout(30000)
describe("/admin/collections", () => {
let medusaProcess
let dbConnection
beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", ".."))
dbConnection = await initDb({ cwd })
medusaProcess = await setupServer({ cwd })
})
afterAll(async () => {
const db = useDb()
await db.shutdown()
medusaProcess.kill()
})
describe("/admin/collections/:id", () => {
beforeEach(async () => {
try {
await adminSeeder(dbConnection)
await productSeeder(dbConnection)
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("updates a collection", async () => {
const api = useApi()
const creationResponse = await api.post(
"/admin/collections",
{
title: "test",
},
{ headers: { Authorization: "Bearer test_token" } }
)
const response = await api.post(
`/admin/collections/${creationResponse.data.collection.id}`,
{
title: "test collection creation",
handle: "test-handle-creation",
},
{ headers: { Authorization: "Bearer test_token" } }
)
expect(response.status).toEqual(200)
expect(response.data).toMatchSnapshot({
collection: {
id: expect.stringMatching(/^pcol_*/),
title: "test collection creation",
handle: "test-handle-creation",
created_at: expect.any(String),
updated_at: expect.any(String),
},
})
})
it("deletes a collection", async () => {
const api = useApi()
const creationResponse = await api.post(
"/admin/collections",
{
title: "test",
},
{ headers: { Authorization: "Bearer test_token" } }
)
const response = await api.delete(
`/admin/collections/${creationResponse.data.collection.id}`,
{ headers: { Authorization: "Bearer test_token" } }
)
expect(response.status).toEqual(200)
expect(response.data).toEqual({
id: creationResponse.data.collection.id,
object: "product-collection",
deleted: true,
})
})
it("gets collection", async () => {
const api = useApi()
const response = await api.get("/admin/collections/test-collection", {
headers: { Authorization: "Bearer test_token" },
})
expect(response.data).toMatchSnapshot({
collection: {
id: "test-collection",
created_at: expect.any(String),
updated_at: expect.any(String),
},
})
})
})
describe("/admin/collections", () => {
beforeEach(async () => {
try {
await adminSeeder(dbConnection)
await productSeeder(dbConnection)
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("creates a collection", async () => {
const api = useApi()
const response = await api.post(
"/admin/collections",
{
title: "test collection creation",
handle: "test-handle-creation",
},
{ headers: { Authorization: "Bearer test_token" } }
)
expect(response.status).toEqual(200)
expect(response.data).toMatchSnapshot({
collection: {
id: expect.stringMatching(/^pcol_*/),
title: "test collection creation",
handle: "test-handle-creation",
created_at: expect.any(String),
updated_at: expect.any(String),
},
})
})
it("lists collections", async () => {
const api = useApi()
const response = await api.get("/admin/collections", {
headers: { Authorization: "Bearer test_token" },
})
expect(response.data).toMatchSnapshot({
collections: [
{
id: "test-collection",
handle: "test-collection",
title: "Test collection",
products: [
{
collection_id: "test-collection",
created_at: expect.any(String),
updated_at: expect.any(String),
profile_id: expect.stringMatching(/^sp_*/),
},
{
collection_id: "test-collection",
created_at: expect.any(String),
updated_at: expect.any(String),
profile_id: expect.stringMatching(/^sp_*/),
},
],
},
{
id: "test-collection1",
handle: "test-collection1",
title: "Test collection 1",
products: [
{
collection_id: "test-collection1",
created_at: expect.any(String),
updated_at: expect.any(String),
profile_id: expect.stringMatching(/^sp_*/),
},
{
collection_id: "test-collection1",
created_at: expect.any(String),
updated_at: expect.any(String),
profile_id: expect.stringMatching(/^sp_*/),
},
],
},
{
id: "test-collection2",
handle: "test-collection2",
title: "Test collection 2",
products: [
{
collection_id: "test-collection2",
created_at: expect.any(String),
updated_at: expect.any(String),
profile_id: expect.stringMatching(/^sp_*/),
},
],
},
],
count: 3,
})
})
})
})
@@ -1,4 +1,3 @@
const { dropDatabase } = require("pg-god")
const path = require("path")
const setupServer = require("../../../helpers/setup-server")
@@ -158,6 +157,7 @@ describe("/admin/customers", () => {
first_name: "newf",
last_name: "newl",
email: "new@email.com",
metadata: { foo: "bar" },
},
{
headers: {
@@ -175,6 +175,7 @@ describe("/admin/customers", () => {
first_name: "newf",
last_name: "newl",
email: "new@email.com",
metadata: { foo: "bar" },
})
)
})
+406 -49
View File
@@ -5,6 +5,8 @@ const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder")
const discountSeeder = require("../../helpers/discount-seeder")
const { exportAllDeclaration } = require("@babel/types")
jest.setTimeout(30000)
@@ -27,32 +29,42 @@ describe("/admin/discounts", () => {
describe("GET /admin/discounts", () => {
beforeEach(async () => {
const manager = dbConnection.manager
try {
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule",
description: "Test discount rule",
type: "percentage",
value: 10,
allocation: "total",
})
await manager.insert(Discount, {
id: "test-discount",
code: "TESTING",
rule_id: "test-discount-rule",
is_dynamic: false,
is_disabled: false,
})
await manager.insert(Discount, {
id: "messi-discount",
code: "BARCA100",
rule_id: "test-discount-rule",
is_dynamic: false,
is_disabled: false,
})
} catch (err) {
throw err
}
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule",
description: "Test discount rule",
type: "percentage",
value: 10,
allocation: "total",
})
await manager.insert(Discount, {
id: "test-discount",
code: "TESTING",
rule_id: "test-discount-rule",
is_dynamic: false,
is_disabled: false,
})
await manager.insert(Discount, {
id: "messi-discount",
code: "BARCA100",
rule_id: "test-discount-rule",
is_dynamic: false,
is_disabled: false,
})
await manager.insert(Discount, {
id: "dynamic-discount",
code: "Dyn100",
rule_id: "test-discount-rule",
is_dynamic: true,
is_disabled: false,
})
await manager.insert(Discount, {
id: "disabled-discount",
code: "Dis100",
rule_id: "test-discount-rule",
is_dynamic: false,
is_disabled: true,
})
})
afterEach(async () => {
@@ -83,12 +95,57 @@ describe("/admin/discounts", () => {
])
)
})
it("lists dynamic discounts ", async () => {
const api = useApi()
const response = await api
.get("/admin/discounts?is_dynamic=true", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.count).toEqual(1)
expect(response.data.discounts).toEqual([
expect.objectContaining({
id: "dynamic-discount",
code: "Dyn100",
}),
])
})
it("lists disabled discounts ", async () => {
const api = useApi()
const response = await api
.get("/admin/discounts?is_disabled=true", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.count).toEqual(1)
expect(response.data.discounts).toEqual([
expect.objectContaining({
id: "disabled-discount",
code: "Dis100",
}),
])
})
})
describe("POST /admin/discounts", () => {
beforeEach(async () => {
try {
await adminSeeder(dbConnection)
await discountSeeder(dbConnection)
} catch (err) {
console.log(err)
throw err
@@ -100,6 +157,60 @@ describe("/admin/discounts", () => {
await db.teardown()
})
it("creates a discount with a rule", async () => {
const api = useApi()
const response = await api
.post(
"/admin/discounts",
{
code: "HELLOWORLD",
rule: {
description: "test",
type: "percentage",
value: 10,
allocation: "total",
},
usage_limit: 10,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.discount).toEqual(
expect.objectContaining({
code: "HELLOWORLD",
usage_limit: 10,
})
)
const test = await api.get(
`/admin/discounts/${response.data.discount.id}`,
{ headers: { Authorization: "Bearer test_token" } }
)
expect(test.status).toEqual(200)
expect(test.data.discount).toEqual(
expect.objectContaining({
code: "HELLOWORLD",
usage_limit: 10,
rule: expect.objectContaining({
value: 10,
type: "percentage",
description: "test",
allocation: "total",
}),
})
)
})
it("creates a discount and updates it", async () => {
const api = useApi()
@@ -159,6 +270,256 @@ describe("/admin/discounts", () => {
)
})
it("automatically sets the code to an uppercase string on update", async () => {
const api = useApi()
const response = await api
.post(
"/admin/discounts",
{
code: "HELLOworld",
rule: {
description: "test",
type: "percentage",
value: 10,
allocation: "total",
},
usage_limit: 10,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.discount).toEqual(
expect.objectContaining({
code: "HELLOWORLD",
usage_limit: 10,
})
)
const updated = await api
.post(
`/admin/discounts/${response.data.discount.id}`,
{
code: "HELLOWORLD_test",
usage_limit: 20,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(updated.status).toEqual(200)
expect(updated.data.discount).toEqual(
expect.objectContaining({
code: "HELLOWORLD_TEST",
usage_limit: 20,
})
)
})
it("creates a dynamic discount and updates it", async () => {
const api = useApi()
const response = await api
.post(
"/admin/discounts",
{
code: "HELLOWORLD_DYNAMIC",
is_dynamic: true,
rule: {
description: "test",
type: "percentage",
value: 10,
allocation: "total",
},
usage_limit: 10,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.discount).toEqual(
expect.objectContaining({
code: "HELLOWORLD_DYNAMIC",
usage_limit: 10,
is_dynamic: true,
})
)
const updated = await api
.post(
`/admin/discounts/${response.data.discount.id}`,
{
usage_limit: 20,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(updated.status).toEqual(200)
expect(updated.data.discount).toEqual(
expect.objectContaining({
code: "HELLOWORLD_DYNAMIC",
usage_limit: 20,
is_dynamic: true,
})
)
})
it("fails to create a fixed discount with multiple regions", async () => {
expect.assertions(2)
const api = useApi()
await api
.post(
"/admin/discounts",
{
code: "HELLOWORLD",
is_dynamic: true,
rule: {
description: "test",
type: "fixed",
value: 10,
allocation: "total",
},
usage_limit: 10,
regions: ["test-region", "test-region-2"],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
expect(err.response.status).toEqual(400)
expect(err.response.data.message).toEqual(
`Fixed discounts can have one region`
)
})
})
it("fails to update a fixed discount with multiple regions", async () => {
expect.assertions(2)
const api = useApi()
const response = await api
.post(
"/admin/discounts",
{
code: "HELLOWORLD",
rule: {
description: "test",
type: "fixed",
value: 10,
allocation: "total",
},
usage_limit: 10,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
await api
.post(
`/admin/discounts/${response.data.discount.id}`,
{
regions: ["test-region", "test-region-2"],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
expect(err.response.status).toEqual(400)
expect(err.response.data.message).toEqual(
`Fixed discounts can have one region`
)
})
})
it("fails to add a region to a fixed discount with an existing region", async () => {
expect.assertions(2)
const api = useApi()
const response = await api
.post(
"/admin/discounts",
{
code: "HELLOWORLD",
rule: {
description: "test",
type: "fixed",
value: 10,
allocation: "total",
},
usage_limit: 10,
regions: ["test-region"],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
await api
.post(
`/admin/discounts/${response.data.discount.id}/regions/test-region-2`,
{},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
expect(err.response.status).toEqual(400)
expect(err.response.data.message).toEqual(
`Fixed discounts can have one region`
)
})
})
it("creates a discount with start and end dates", async () => {
const api = useApi()
@@ -338,11 +699,11 @@ describe("/admin/discounts", () => {
)
.catch((err) => {
expect(err.response.status).toEqual(400)
expect(err.response.data.message).toEqual([
expect(err.response.data).toEqual(
expect.objectContaining({
message: `"ends_at" must be greater than "ref:starts_at"`,
}),
])
message: `"ends_at" must be greater than "starts_at"`,
})
)
})
})
})
@@ -351,25 +712,21 @@ describe("/admin/discounts", () => {
let manager
beforeEach(async () => {
manager = dbConnection.manager
try {
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule",
description: "Test discount rule",
type: "percentage",
value: 10,
allocation: "total",
})
await manager.insert(Discount, {
id: "test-discount",
code: "TESTING",
rule_id: "test-discount-rule",
is_dynamic: false,
is_disabled: false,
})
} catch (err) {
throw err
}
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule",
description: "Test discount rule",
type: "percentage",
value: 10,
allocation: "total",
})
await manager.insert(Discount, {
id: "test-discount",
code: "TESTING",
rule_id: "test-discount-rule",
is_dynamic: false,
is_disabled: false,
})
})
afterEach(async () => {
@@ -158,12 +158,15 @@ describe("/admin/gift-cards", () => {
it("creates a gift card", async () => {
const api = useApi()
const dateString = new Date().toISOString()
const response = await api
.post(
"/admin/gift-cards",
{
value: 1000,
region_id: "region",
ends_at: dateString,
},
{
headers: {
+94 -5
View File
@@ -3,7 +3,6 @@ const {
ReturnReason,
Order,
LineItem,
ProductVariant,
CustomShippingOption,
} = require("@medusajs/medusa")
@@ -74,6 +73,59 @@ describe("/admin/orders", () => {
})
})
describe("POST /admin/orders/:id", () => {
beforeEach(async () => {
await adminSeeder(dbConnection)
await orderSeeder(dbConnection)
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("updates a shipping adress", async () => {
const api = useApi()
const response = await api
.post(
"/admin/orders/test-order",
{
email: "test@test.com",
shipping_address: {
address_1: "Some Street",
address_2: "",
province: "",
postal_code: "1235",
city: "losangeles",
country_code: "us",
},
},
{
headers: {
authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.order.shipping_address).toMatchSnapshot({
id: expect.any(String),
address_1: "Some Street",
address_2: "",
province: "",
postal_code: "1235",
city: "losangeles",
country_code: "us",
created_at: expect.any(String),
updated_at: expect.any(String),
})
})
})
describe("GET /admin/orders", () => {
beforeEach(async () => {
try {
@@ -163,7 +215,6 @@ describe("/admin/orders", () => {
it("cancels an order and increments inventory_quantity", async () => {
const api = useApi()
const manager = dbConnection.manager
const initialInventoryRes = await api.get("/store/variants/test-variant")
@@ -1086,7 +1137,7 @@ describe("/admin/orders", () => {
}
)
//Find variant that should have its inventory_quantity updated
// Find variant that should have its inventory_quantity updated
const toTest = returned.data.order.items.find((i) => i.id === "test-item")
expect(returned.status).toEqual(200)
@@ -1119,7 +1170,7 @@ describe("/admin/orders", () => {
}
)
//Find variant that should have its inventory_quantity updated
// Find variant that should have its inventory_quantity updated
const toTest = returned.data.order.items.find((i) => i.id === "test-item")
expect(returned.status).toEqual(200)
@@ -1178,6 +1229,44 @@ describe("/admin/orders", () => {
])
})
it("lists all orders with a fulfillment status = fulfilled", async () => {
const api = useApi()
const response = await api
.get("/admin/orders?fulfillment_status[]=fulfilled", {
headers: {
authorization: "Bearer test_token",
},
})
.catch((err) => console.log(err))
expect(response.status).toEqual(200)
expect(response.data.orders).toEqual([
expect.objectContaining({
id: "test-order",
}),
])
})
it("fails to lists all orders with an invalid status", async () => {
expect.assertions(3)
const api = useApi()
await api
.get("/admin/orders?status[]=test", {
headers: {
authorization: "Bearer test_token",
},
})
.catch((err) => {
expect(err.response.status).toEqual(400)
expect(err.response.data.type).toEqual("invalid_data")
expect(err.response.data.message).toEqual(
"each value in status must be a valid enum value"
)
})
})
it("list all orders with matching order email", async () => {
const api = useApi()
@@ -1671,7 +1760,7 @@ describe("/admin/orders", () => {
expect(returnOnOrder.status).toEqual(200)
const captured = await api.post(
await api.post(
"/admin/orders/test-order/capture",
{},
{
+127 -11
View File
@@ -6,6 +6,7 @@ const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder")
const productSeeder = require("../../helpers/product-seeder")
const { ProductVariant } = require("@medusajs/medusa")
jest.setTimeout(50000)
@@ -105,7 +106,7 @@ describe("/admin/products", () => {
status: "proposed",
}
//update test-product status to proposed
// update test-product status to proposed
await api
.post("/admin/products/test-product", payload, {
headers: {
@@ -143,6 +144,9 @@ describe("/admin/products", () => {
const notExpected = [
expect.objectContaining({ status: "draft" }),
expect.objectContaining({ status: "rejected" }),
expect.objectContaining({
id: "test-product_filtering_4",
}),
]
const response = await api
@@ -174,6 +178,48 @@ describe("/admin/products", () => {
}
})
it("returns a list of deleted products with free text query", async () => {
const api = useApi()
const response = await api
.get("/admin/products?deleted_at[gt]=01-26-1990&q=test", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.products).toEqual([
expect.objectContaining({
id: "test-product_filtering_4",
}),
])
})
it("returns a list of deleted products", async () => {
const api = useApi()
const response = await api
.get("/admin/products?deleted_at[gt]=01-26-1990", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.products).toEqual([
expect.objectContaining({
id: "test-product_filtering_4",
}),
])
})
it("returns a list of products in collection", async () => {
const api = useApi()
@@ -294,7 +340,7 @@ describe("/admin/products", () => {
}
})
it("returns a list of products with giftcard in list", async () => {
it("returns a list of products with only giftcard in list", async () => {
const api = useApi()
const payload = {
@@ -423,7 +469,7 @@ describe("/admin/products", () => {
],
variants: [
{
id: "test-variant", //expect.stringMatching(/^test-variant*/),
id: "test-variant", // expect.stringMatching(/^test-variant*/),
created_at: expect.any(String),
updated_at: expect.any(String),
product_id: expect.stringMatching(/^test-*/),
@@ -446,7 +492,7 @@ describe("/admin/products", () => {
],
},
{
id: "test-variant_2", //expect.stringMatching(/^test-variant*/),
id: "test-variant_2", // expect.stringMatching(/^test-variant*/),
created_at: expect.any(String),
updated_at: expect.any(String),
product_id: expect.stringMatching(/^test-*/),
@@ -519,7 +565,7 @@ describe("/admin/products", () => {
options: [],
variants: [
{
id: "test-variant_4", //expect.stringMatching(/^test-variant*/),
id: "test-variant_4", // expect.stringMatching(/^test-variant*/),
created_at: expect.any(String),
updated_at: expect.any(String),
product_id: expect.stringMatching(/^test-*/),
@@ -542,7 +588,7 @@ describe("/admin/products", () => {
],
},
{
id: "test-variant_3", //expect.stringMatching(/^test-variant*/),
id: "test-variant_3", // expect.stringMatching(/^test-variant*/),
created_at: expect.any(String),
updated_at: expect.any(String),
product_id: expect.stringMatching(/^test-*/),
@@ -595,7 +641,6 @@ describe("/admin/products", () => {
options: expect.any(Array),
tags: expect.any(Array),
variants: expect.any(Array),
created_at: expect.any(String),
updated_at: expect.any(String),
},
{
@@ -607,7 +652,6 @@ describe("/admin/products", () => {
options: expect.any(Array),
tags: expect.any(Array),
variants: expect.any(Array),
created_at: expect.any(String),
updated_at: expect.any(String),
},
{
@@ -619,7 +663,6 @@ describe("/admin/products", () => {
options: expect.any(Array),
tags: expect.any(Array),
variants: expect.any(Array),
created_at: expect.any(String),
updated_at: expect.any(String),
},
])
@@ -736,6 +779,46 @@ describe("/admin/products", () => {
)
})
it("creates a product that is not discountable", async () => {
const api = useApi()
const payload = {
title: "Test",
discountable: false,
description: "test-product-description",
type: { value: "test-type" },
images: ["test-image.png", "test-image-2.png"],
collection_id: "test-collection",
tags: [{ value: "123" }, { value: "456" }],
options: [{ title: "size" }, { title: "color" }],
variants: [
{
title: "Test variant",
inventory_quantity: 10,
prices: [{ currency_code: "usd", amount: 100 }],
options: [{ value: "large" }, { value: "green" }],
},
],
}
const response = await api
.post("/admin/products", payload, {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.product).toEqual(
expect.objectContaining({
discountable: false,
})
)
})
it("Sets variant ranks when creating a product", async () => {
const api = useApi()
@@ -844,7 +927,6 @@ describe("/admin/products", () => {
const payload = {
collection_id: null,
type: null,
variants: [
{
id: "test-variant",
@@ -898,7 +980,6 @@ describe("/admin/products", () => {
],
}),
],
type: null,
status: "published",
collection: null,
type: expect.objectContaining({
@@ -1074,6 +1155,41 @@ describe("/admin/products", () => {
)
})
it("successfully deletes a product and variants", async () => {
const api = useApi()
const variantPre = await dbConnection.manager.findOne(ProductVariant, {
id: "test-variant",
})
expect(variantPre).not.toEqual(undefined)
const response = await api
.delete("/admin/products/test-product", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data).toEqual(
expect.objectContaining({
id: "test-product",
deleted: true,
})
)
const variant = await dbConnection.manager.findOne(ProductVariant, {
id: "test-variant",
})
expect(variant).toEqual(undefined)
})
it("successfully creates product with soft-deleted product handle and deletes it again", async () => {
const api = useApi()
@@ -0,0 +1,78 @@
const path = require("path")
const { Region, FulfillmentProvider } = require("@medusajs/medusa")
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder")
jest.setTimeout(30000)
describe("/admin/discounts", () => {
let medusaProcess
let dbConnection
beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", ".."))
dbConnection = await initDb({ cwd })
medusaProcess = await setupServer({ cwd })
})
afterAll(async () => {
const db = useDb()
await db.shutdown()
medusaProcess.kill()
})
describe("DELETE /admin/regions/:id", () => {
beforeEach(async () => {
const manager = dbConnection.manager
await adminSeeder(dbConnection)
await manager.insert(Region, {
id: "test-region",
name: "Test Region",
currency_code: "usd",
tax_rate: 0,
})
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("successfully deletes a region with a fulfillment provider", async () => {
const api = useApi()
// add fulfillment provider to the region
await api.post(
"/admin/regions/test-region",
{
fulfillment_providers: ["test-ful"],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
const response = await api
.delete(`/admin/regions/test-region`, {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(response.data).toEqual({
id: "test-region",
object: "region",
deleted: true,
})
expect(response.status).toEqual(200)
})
})
})
@@ -12,7 +12,7 @@ Object {
"last_name": "testesen",
"metadata": null,
"orders": Array [],
"phone": "12345678",
"phone": null,
"updated_at": Any<String>,
}
`;
@@ -0,0 +1,52 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`/store/collections /store/collections lists collections 1`] = `
Object {
"collections": Array [
Object {
"created_at": Any<String>,
"deleted_at": null,
"handle": "test-collection",
"id": "test-collection",
"metadata": null,
"title": "Test collection",
"updated_at": Any<String>,
},
Object {
"created_at": Any<String>,
"deleted_at": null,
"handle": "test-collection1",
"id": "test-collection1",
"metadata": null,
"title": "Test collection 1",
"updated_at": Any<String>,
},
Object {
"created_at": Any<String>,
"deleted_at": null,
"handle": "test-collection2",
"id": "test-collection2",
"metadata": null,
"title": "Test collection 2",
"updated_at": Any<String>,
},
],
"count": 3,
"limit": 10,
"offset": 0,
}
`;
exports[`/store/collections /store/collections/:id gets collection 1`] = `
Object {
"collection": Object {
"created_at": Any<String>,
"deleted_at": null,
"handle": "test-collection",
"id": "test-collection",
"metadata": null,
"title": "Test collection",
"updated_at": Any<String>,
},
}
`;
@@ -141,6 +141,18 @@ Object {
"material": null,
"metadata": null,
"mid_code": null,
"options": Array [
Object {
"created_at": Any<String>,
"deleted_at": null,
"id": "test-variant-option",
"metadata": null,
"option_id": "test-option",
"updated_at": Any<String>,
"value": "Default variant",
"variant_id": "test-variant",
},
],
"origin_country": null,
"prices": Array [
Object {
@@ -178,6 +190,18 @@ Object {
"material": null,
"metadata": null,
"mid_code": null,
"options": Array [
Object {
"created_at": Any<String>,
"deleted_at": null,
"id": "test-variant-option-2",
"metadata": null,
"option_id": "test-option",
"updated_at": Any<String>,
"value": "Default variant 2",
"variant_id": "test-variant_2",
},
],
"origin_country": null,
"prices": Array [
Object {
@@ -215,6 +239,18 @@ Object {
"material": null,
"metadata": null,
"mid_code": null,
"options": Array [
Object {
"created_at": Any<String>,
"deleted_at": null,
"id": "test-variant-option-1",
"metadata": null,
"option_id": "test-option",
"updated_at": Any<String>,
"value": "Default variant 1",
"variant_id": "test-variant_1",
},
],
"origin_country": null,
"prices": Array [
Object {
@@ -1,11 +1,8 @@
const path = require("path")
const { Region, DiscountRule, Discount } = require("@medusajs/medusa")
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder")
const { exportAllDeclaration } = require("@babel/types")
jest.setTimeout(30000)
@@ -34,7 +31,6 @@ describe("/admin/auth", () => {
password: "secret_password",
first_name: "test",
last_name: "testesen",
phone: "12345678",
})
.catch((err) => {
console.log(err)
@@ -57,7 +53,7 @@ describe("/admin/auth", () => {
updated_at: expect.any(String),
first_name: "test",
last_name: "testesen",
phone: "12345678",
phone: null,
email: "test@testesen.dk",
})
})
@@ -378,7 +378,7 @@ describe("/store/carts", () => {
expect(e.response.status).toBe(409)
}
//check to see if payment has been cancelled and cart is not completed
// check to see if payment has been cancelled and cart is not completed
const res = await api.get(`/store/carts/test-cart-2`)
expect(res.data.cart.payment.canceled_at).not.toBe(null)
expect(res.data.cart.completed_at).toBe(null)
@@ -414,7 +414,7 @@ describe("/store/carts", () => {
expect(e.response.status).toBe(409)
}
//check to see if payment has been cancelled and cart is not completed
// check to see if payment has been cancelled and cart is not completed
const res = await api.get(`/store/carts/swap-cart`)
expect(res.data.cart.payment_authorized_at).toBe(null)
expect(res.data.cart.payment.canceled_at).not.toBe(null)
@@ -450,7 +450,7 @@ describe("/store/carts", () => {
console.log(error)
}
//check to see if payment is authorized and cart is completed
// check to see if payment is authorized and cart is completed
const res = await api.get(`/store/carts/swap-cart`)
expect(res.data.cart.payment_authorized_at).not.toBe(null)
expect(res.data.cart.completed_at).not.toBe(null)
@@ -477,7 +477,7 @@ describe("/store/carts", () => {
type: "swap",
})
let cartWithCustomSo = await manager.save(_cart)
const cartWithCustomSo = await manager.save(_cart)
await manager.insert(CustomShippingOption, {
id: "another-cso-test",
@@ -683,7 +683,7 @@ describe("/store/carts", () => {
it("updates empty cart.customer_id on cart retrieval", async () => {
const api = useApi()
let customer = await api.post(
const customer = await api.post(
"/store/customers",
{
email: "oli@test.dk",
@@ -712,7 +712,7 @@ describe("/store/carts", () => {
it("updates cart.customer_id on cart retrieval if cart.customer_id differ from session customer", async () => {
const api = useApi()
let customer = await api.post(
const customer = await api.post(
"/store/customers",
{
email: "oli@test.dk",
@@ -0,0 +1,100 @@
const { ProductCollection } = require("@medusajs/medusa")
const path = require("path")
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const productSeeder = require("../../helpers/product-seeder")
jest.setTimeout(30000)
describe("/store/collections", () => {
let medusaProcess
let dbConnection
beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", ".."))
dbConnection = await initDb({ cwd })
medusaProcess = await setupServer({ cwd })
})
afterAll(async () => {
const db = useDb()
await db.shutdown()
medusaProcess.kill()
})
describe("/store/collections/:id", () => {
beforeEach(async () => {
try {
await productSeeder(dbConnection)
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("gets collection", async () => {
const api = useApi()
const response = await api.get("/store/collections/test-collection")
expect(response.data).toMatchSnapshot({
collection: {
id: "test-collection",
created_at: expect.any(String),
updated_at: expect.any(String),
},
})
})
})
describe("/store/collections", () => {
beforeEach(async () => {
try {
await productSeeder(dbConnection)
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("lists collections", async () => {
const api = useApi()
const response = await api.get("/store/collections")
expect(response.data).toMatchSnapshot({
collections: [
{
id: "test-collection",
created_at: expect.any(String),
updated_at: expect.any(String),
},
{
id: "test-collection1",
created_at: expect.any(String),
updated_at: expect.any(String),
},
{
id: "test-collection2",
created_at: expect.any(String),
updated_at: expect.any(String),
},
],
count: 3,
limit: 10,
offset: 0,
})
})
})
})
@@ -5,8 +5,6 @@ const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const customerSeeder = require("../../helpers/customer-seeder")
jest.setTimeout(30000)
describe("/store/customers", () => {
@@ -113,21 +111,22 @@ describe("/store/customers", () => {
password: "test",
})
const customerId = authResponse.data.customer.id
const [authCookie] = authResponse.headers["set-cookie"][0].split(";")
const response = await api.post(
`/store/customers/me`,
{
password: "test",
metadata: { key: "value" },
},
{
headers: {
Cookie: authCookie,
const response = await api
.post(
`/store/customers/me`,
{
password: "test",
metadata: { key: "value" },
},
}
)
{
headers: {
Cookie: authCookie,
},
}
)
.catch((e) => console.log("err", e))
expect(response.status).toEqual(200)
expect(response.data.customer).not.toHaveProperty("password_hash")
@@ -146,7 +145,6 @@ describe("/store/customers", () => {
password: "test",
})
const customerId = authResponse.data.customer.id
const [authCookie] = authResponse.headers["set-cookie"][0].split(";")
const response = await api.post(
@@ -192,7 +190,6 @@ describe("/store/customers", () => {
password: "test",
})
const customerId = authResponse.data.customer.id
const [authCookie] = authResponse.headers["set-cookie"][0].split(";")
const response = await api.post(
@@ -230,7 +227,6 @@ describe("/store/customers", () => {
password: "test",
})
const customerId = authResponse.data.customer.id
const [authCookie] = authResponse.headers["set-cookie"][0].split(";")
const check = await api.post(
@@ -68,6 +68,12 @@ describe("/store/products", () => {
product_id: "test-product",
created_at: expect.any(String),
updated_at: expect.any(String),
options: [
{
created_at: expect.any(String),
updated_at: expect.any(String),
},
],
prices: [
{
id: "test-money-amount",
@@ -105,6 +111,12 @@ describe("/store/products", () => {
product_id: "test-product",
created_at: expect.any(String),
updated_at: expect.any(String),
options: [
{
created_at: expect.any(String),
updated_at: expect.any(String),
},
],
prices: [
{
id: "test-money-amount",
@@ -117,7 +129,6 @@ describe("/store/products", () => {
id: "test-price2",
region_id: null,
sale_amount: null,
updated_at: expect.any(String),
variant_id: "test-variant_2",
},
],
@@ -142,6 +153,12 @@ describe("/store/products", () => {
product_id: "test-product",
created_at: expect.any(String),
updated_at: expect.any(String),
options: [
{
created_at: expect.any(String),
updated_at: expect.any(String),
},
],
prices: [
{
id: "test-money-amount",
@@ -254,16 +271,6 @@ describe("/store/products", () => {
})
})
it("Fetching variant options without additional relation fails", async () => {
const api = useApi()
const response = await api.get("/store/products/test-product")
const product = response.data.product
expect(product.variants.some((variant) => variant.options)).toEqual(false)
})
it("lists all published products", async () => {
const api = useApi()
@@ -24,6 +24,49 @@ describe("/store/return-reasons", () => {
medusaProcess.kill()
})
describe("GET /store/return-reasons/:id", () => {
let rrId
beforeEach(async () => {
try {
const created = dbConnection.manager.create(ReturnReason, {
value: "wrong_size",
label: "Wrong size",
})
const result = await dbConnection.manager.save(created)
rrId = result.id
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("get a return reason", async () => {
const api = useApi()
const response = await api
.get(`/store/return-reasons/${rrId}`)
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.return_reason).toEqual(
expect.objectContaining({
id: rrId,
value: "wrong_size",
})
)
})
})
describe("GET /store/return-reasons", () => {
let rrId
let rrId_1
@@ -249,6 +249,29 @@ describe("/store/carts", () => {
])
})
it("failes to create a return with an invalid quantity (less than 1)", async () => {
const api = useApi()
const response = await api
.post("/store/returns", {
order_id: "order_test",
items: [
{
reason_id: rrId,
note: "TOO small",
item_id: "test-item",
quantity: 0,
},
],
})
.catch((err) => {
return err.response
})
expect(response.status).toEqual(400)
expect(response.data.type).toEqual("invalid_data")
})
it("creates a return with discount and non-discountable item", async () => {
const api = useApi()
@@ -0,0 +1,35 @@
const {
ShippingProfile,
Region,
Discount,
DiscountRule,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
await manager.insert(Region, {
id: "test-region",
name: "Test Region",
currency_code: "usd",
tax_rate: 0,
payment_providers: [
{
id: "test-pay",
is_installed: true,
},
],
})
await manager.insert(Region, {
id: "test-region-2",
name: "Test Region 2",
currency_code: "eur",
tax_rate: 0,
payment_providers: [
{
id: "test-pay",
is_installed: true,
},
],
})
}
@@ -271,4 +271,16 @@ module.exports = async (connection, data = {}) => {
})
await manager.save(product3)
const product4 = manager.create(Product, {
id: "test-product_filtering_4",
handle: "test-product_filtering_4",
title: "Test product filtering 4",
profile_id: defaultProfile.id,
description: "test-product-description",
status: "proposed",
deleted_at: new Date().toISOString(),
})
await manager.save(product4)
}
+4 -4
View File
@@ -8,15 +8,15 @@
"build": "babel src -d dist --extensions \".ts,.js\""
},
"dependencies": {
"@medusajs/medusa": "1.1.41-dev-1634316075104",
"medusa-interfaces": "1.1.23-dev-1634316075104",
"@medusajs/medusa": "1.1.51",
"medusa-interfaces": "1.1.27",
"typeorm": "^0.2.31"
},
"devDependencies": {
"@babel/cli": "^7.12.10",
"@babel/core": "^7.12.10",
"@babel/node": "^7.12.10",
"babel-preset-medusa-package": "1.1.15-dev-1634316075104",
"babel-preset-medusa-package": "1.1.17",
"jest": "^26.6.3"
}
}
}
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -19,7 +19,7 @@
"babel-jest": "^26.6.3",
"babel-preset-medusa-package": "^1.0.0",
"cross-env": "^7.0.2",
"eslint": "^8.0.0",
"eslint": "^8.2.0",
"eslint-config-google": "^0.14.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
@@ -57,7 +57,7 @@
"@docusaurus/theme-search-algolia": "^2.0.0-beta.3",
"global": "^4.4.0",
"import-from": "^3.0.0",
"oas-normalize": "^2.3.1",
"oas-normalize": "^5.0.1",
"swagger-inline": "^3.2.2"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"plugins": ["@babel/plugin-proposal-class-properties"],
"presets": ["@babel/preset-env"],
"presets": ["@babel/preset-env", "@babel/preset-typescript"],
"env": {
"test": {
"plugins": ["@babel/plugin-transform-runtime"]
+10
View File
@@ -3,6 +3,16 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.28](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.27...medusa-core-utils@1.1.28) (2021-11-19)
**Note:** Version bump only for package medusa-core-utils
## [1.1.27](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.26...medusa-core-utils@1.1.27) (2021-11-19)
### Features
- Typescript for API layer ([#817](https://github.com/medusajs/medusa/issues/817)) ([373532e](https://github.com/medusajs/medusa/commit/373532ecbc8196f47e71af95a8cf82a14a4b1f9e))
## [1.1.26](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.25...medusa-core-utils@1.1.26) (2021-10-18)
**Note:** Version bump only for package medusa-core-utils
+8 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-core-utils",
"version": "1.1.26",
"version": "1.1.28",
"description": "Core utils for Medusa",
"main": "dist/index.js",
"repository": {
@@ -10,7 +10,7 @@
},
"scripts": {
"test": "jest",
"build": "babel src --out-dir dist/ --ignore **/__tests__",
"build": "tsc --build",
"prepare": "cross-env NODE_ENV=production npm run build",
"watch": "babel -w src --out-dir dist/ --ignore **/__tests__"
},
@@ -23,15 +23,19 @@
"@babel/plugin-transform-classes": "^7.9.5",
"@babel/plugin-transform-runtime": "^7.7.6",
"@babel/preset-env": "^7.13.9",
"@babel/preset-typescript": "^7.16.0",
"@babel/runtime": "^7.13.9",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"prettier": "^1.19.1"
"prettier": "^1.19.1",
"typescript": "^4.4.4"
},
"dependencies": {
"joi": "^17.3.0",
"joi-objectid": "^3.0.1"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
@@ -22,12 +22,21 @@ export const MedusaErrorCodes = {
* @extends Error
*/
class MedusaError extends Error {
public type: string
public message: string
public code?: string
public date: Date
public static Types = MedusaErrorTypes
public static Codes = MedusaErrorCodes
/**
* Creates a standardized error to be used across Medusa project.
* @param type {MedusaErrorType} - the type of error.
* @param params {Array} - Error params.
* @param {string} type - type of error
* @param {string} message - message to go along with error
* @param {string} code - code of error
* @param {Array} params - params
*/
constructor(type, message, code, ...params) {
constructor(type: string, message: string, code?: string, ...params: any) {
super(...params)
if (Error.captureStackTrace) {
@@ -35,14 +44,10 @@ class MedusaError extends Error {
}
this.type = type
this.name = type
this.code = code
this.message = message
this.date = new Date()
}
}
MedusaError.Types = MedusaErrorTypes
MedusaError.Codes = MedusaErrorCodes
export default MedusaError
+8 -8
View File
@@ -1,11 +1,11 @@
export { countries } from "./countries"
export { isoCountryLookup } from "./countries"
export { transformIdableFields } from "./transform-idable-fields"
export { indexTypes } from "./index-types"
export { default as Validator } from "./validator"
export { default as compareObjectsByProp } from "./compare-objects"
export { countries, isoCountryLookup } from "./countries"
export { default as createRequireFromPath } from "./create-require-from-path"
export { default as MedusaError } from "./errors"
export { default as getConfigFile } from "./get-config-file"
export { default as createRequireFromPath } from "./create-require-from-path"
export { default as compareObjectsByProp } from "./compare-objects"
export { default as zeroDecimalCurrencies } from "./zero-decimal-currencies"
export { default as humanizeAmount } from "./humanize-amount"
export { indexTypes } from "./index-types"
export { transformIdableFields } from "./transform-idable-fields"
export { default as Validator } from "./validator"
export { default as zeroDecimalCurrencies } from "./zero-decimal-currencies"
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"lib": ["es5", "es6"],
"target": "es5",
"outDir": "./dist",
"esModuleInterop": true,
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"noImplicitReturns": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"allowJs": true,
"skipLibCheck": true
},
"include": ["./src/**/*"],
"exclude": ["./dist/**/*", "./src/__tests__", "node_modules"]
}
File diff suppressed because it is too large Load Diff
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.0.6](https://github.com/medusajs/medusa/compare/medusa-file-s3@1.0.5...medusa-file-s3@1.0.6) (2021-11-19)
**Note:** Version bump only for package medusa-file-s3
## [1.0.5](https://github.com/medusajs/medusa/compare/medusa-file-s3@1.0.4...medusa-file-s3@1.0.5) (2021-11-19)
**Note:** Version bump only for package medusa-file-s3
## [1.0.4](https://github.com/medusajs/medusa/compare/medusa-file-s3@1.0.3...medusa-file-s3@1.0.4) (2021-10-18)
**Note:** Version bump only for package medusa-file-s3
+5 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-file-s3",
"version": "1.0.4",
"version": "1.0.6",
"description": "AWS s3 file connector for Medusa",
"main": "index.js",
"repository": {
@@ -40,7 +40,8 @@
"aws-sdk": "^2.983.0",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26",
"medusa-test-utils": "^1.1.29"
}
"medusa-core-utils": "^1.1.28",
"medusa-test-utils": "^1.1.31"
},
"gitHead": "aa460f63591f9625f1fe98749b34172e528bed7f"
}
+8
View File
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.31](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.30...medusa-file-spaces@1.1.31) (2021-11-19)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.30](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.29...medusa-file-spaces@1.1.30) (2021-11-19)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.29](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.28...medusa-file-spaces@1.1.29) (2021-10-18)
**Note:** Version bump only for package medusa-file-spaces
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-file-spaces",
"version": "1.1.29",
"version": "1.1.31",
"description": "Digital Ocean Spaces file connector for Medusa",
"main": "index.js",
"repository": {
@@ -40,9 +40,9 @@
"aws-sdk": "^2.710.0",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26",
"medusa-test-utils": "^1.1.29",
"medusa-core-utils": "^1.1.28",
"medusa-test-utils": "^1.1.31",
"stripe": "^8.50.0"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "aa460f63591f9625f1fe98749b34172e528bed7f"
}
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.28](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.27...medusa-fulfillment-manual@1.1.28) (2021-11-19)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.27](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.26...medusa-fulfillment-manual@1.1.27) (2021-11-19)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.26](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.25...medusa-fulfillment-manual@1.1.26) (2021-10-18)
**Note:** Version bump only for package medusa-fulfillment-manual
@@ -1,6 +1,6 @@
{
"name": "medusa-fulfillment-manual",
"version": "1.1.26",
"version": "1.1.28",
"description": "A manual fulfillment provider for Medusa",
"main": "index.js",
"repository": {
@@ -36,7 +36,7 @@
"@babel/plugin-transform-instanceof": "^7.8.3",
"@babel/runtime": "^7.7.6",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26"
"medusa-core-utils": "^1.1.28"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.32](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.31...medusa-fulfillment-webshipper@1.1.32) (2021-11-19)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.31](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.30...medusa-fulfillment-webshipper@1.1.31) (2021-11-19)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.30](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.29...medusa-fulfillment-webshipper@1.1.30) (2021-10-18)
**Note:** Version bump only for package medusa-fulfillment-webshipper
@@ -1,6 +1,6 @@
{
"name": "medusa-fulfillment-webshipper",
"version": "1.1.30",
"version": "1.1.32",
"description": "Webshipper Fulfillment provider for Medusa",
"main": "index.js",
"repository": {
@@ -37,7 +37,7 @@
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26"
"medusa-core-utils": "^1.1.28"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
+11
View File
@@ -3,6 +3,17 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.29](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.28...medusa-interfaces@1.1.29) (2021-11-19)
**Note:** Version bump only for package medusa-interfaces
## [1.1.28](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.27...medusa-interfaces@1.1.28) (2021-11-19)
### Features
- Allow retrieval of soft-deleted products ([#723](https://github.com/medusajs/medusa/issues/723)) ([1e50aee](https://github.com/medusajs/medusa/commit/1e50aee4feb55092560dd4a9c51a0671363e8576))
- Typescript for API layer ([#817](https://github.com/medusajs/medusa/issues/817)) ([373532e](https://github.com/medusajs/medusa/commit/373532ecbc8196f47e71af95a8cf82a14a4b1f9e))
## [1.1.27](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.26...medusa-interfaces@1.1.27) (2021-10-18)
**Note:** Version bump only for package medusa-interfaces
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-interfaces",
"version": "1.1.27",
"version": "1.1.29",
"description": "Core interfaces for Medusa",
"main": "dist/index.js",
"repository": {
@@ -35,7 +35,7 @@
"typeorm": "0.x"
},
"dependencies": {
"medusa-core-utils": "^1.1.26"
"medusa-core-utils": "^1.1.28"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
+11 -2
View File
@@ -1,5 +1,5 @@
import { MedusaError } from "medusa-core-utils"
import { In, FindOperator, Raw } from "typeorm"
import { FindOperator, In, Raw } from "typeorm"
/**
* Common functionality for Services
@@ -21,6 +21,11 @@ class BaseService {
buildQuery_(selector, config = {}) {
const build = (obj) => {
const where = Object.entries(obj).reduce((acc, [key, value]) => {
// Undefined values indicate that they have no significance to the query.
// If the query is looking for rows where a column is not set it should use null instead of undefined
if (typeof value === "undefined") {
return acc
}
switch (true) {
case value instanceof FindOperator:
acc[key] = value
@@ -63,13 +68,17 @@ class BaseService {
return acc
}, {})
return where
}
const query = {
where: build(selector),
}
if ("deleted_at" in selector) {
query.withDeleted = true
}
if ("skip" in config) {
query.skip = config.skip
@@ -1,4 +1,4 @@
import { BaseService } from "medusa-interfaces"
import BaseService from "./base-service"
/**
* The interface that all search services must implement.
+2
View File
@@ -0,0 +1,2 @@
node_modules
/dist
+20
View File
@@ -0,0 +1,20 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.0.3](https://github.com/medusajs/medusa-js/compare/@medusajs/medusa-js@1.0.2...@medusajs/medusa-js@1.0.3) (2021-11-19)
### Bug Fixes
- release ([5fa4848](https://github.com/medusajs/medusa-js/commit/5fa4848b17a9dd432c2361e5d9485950494a2bc6))
## [1.0.2](https://github.com/medusajs/medusa-js/compare/@medusajs/medusa-js@1.0.1...@medusajs/medusa-js@1.0.2) (2021-11-19)
**Note:** Version bump only for package @medusajs/medusa-js
## 1.0.1 (2021-11-19)
### Features
- Typescript for API layer ([#817](https://github.com/medusajs/medusa-js/issues/817)) ([373532e](https://github.com/medusajs/medusa-js/commit/373532ecbc8196f47e71af95a8cf82a14a4b1f9e))
+1
View File
@@ -0,0 +1 @@
# Medusa Commerce JS Client
+7
View File
@@ -0,0 +1,7 @@
{
"transform": {
"^.+\\.(t|j)sx?$": "ts-jest"
},
"testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"]
}
+38
View File
@@ -0,0 +1,38 @@
{
"name": "@medusajs/medusa-js",
"version": "1.0.3",
"description": "Client for Medusa Commerce Rest API",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist/**/*"
],
"scripts": {
"prepare": "cross-env NODE_ENV=production npm run build",
"build": "tsc --build",
"test": "jest --config jestconfig.json"
},
"author": "Oliver Juhl",
"license": "MIT",
"dependencies": {
"@medusajs/medusa": "^1.1.55",
"axios": "^0.21.0",
"retry-axios": "^2.6.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/medusajs/medusa-js.git"
},
"bugs": {
"url": "https://github.com/medusajs/medusa-js/issues"
},
"devDependencies": {
"@types/jest": "^26.0.19",
"cross-env": "^7.0.3",
"eslint": "^8.2.0",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"typescript": "^4.1.3"
},
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
+57
View File
@@ -0,0 +1,57 @@
"use strict"
/**
* MedusaError is the base error for every other MedusaError
*/
export default class MedusaError extends Error {
constructor() {
super()
}
public static factory(type: ErrorType): MedusaError {
switch (type) {
case ErrorType.INVALID_REQUEST:
return new MedusaInvalidRequestError()
case ErrorType.AUTHENTICATION:
return new MedusaAuthenticationError()
case ErrorType.API:
return new MedusaAPIError()
case ErrorType.PERMISSION:
return new MedusaPermissionError()
case ErrorType.CONNECTION:
return new MedusaConnectionError()
}
}
}
enum ErrorType {
"INVALID_REQUEST",
"API",
"AUTHENTICATION",
"PERMISSION",
"CONNECTION",
}
/**
* MedusaInvalidRequestError is raised when a request as invalid parameters.
*/
export class MedusaInvalidRequestError extends MedusaError {}
/**
* MedusaAPIError is raised in case no other type cover the problem
*/
export class MedusaAPIError extends MedusaError {}
/**
* MedusaAuthenticationError is raised when invalid credentials is used to connect to Medusa
*/
export class MedusaAuthenticationError extends MedusaError {}
/**
* MedusaPermissionErorr is raised when attempting to access a resource without permissions
*/
export class MedusaPermissionError extends MedusaError {}
/**
* MedusaConnectionError is raised when the Medusa servers can't be reached.
*/
export class MedusaConnectionError extends MedusaError {}
+51
View File
@@ -0,0 +1,51 @@
import MedusaError from "./error"
import Client, { Config } from "./request"
import AuthResource from "./resources/auth"
import CartsResource from "./resources/carts"
import CollectionsResource from "./resources/collections"
import CustomersResource from "./resources/customers"
import GiftCardsResource from "./resources/gift-cards"
import OrdersResource from "./resources/orders"
import ProductsResource from "./resources/products"
import RegionsResource from "./resources/regions"
import ReturnReasonsResource from "./resources/return-reasons"
import ReturnsResource from "./resources/returns"
import ShippingOptionsResource from "./resources/shipping-options"
import SwapsResource from "./resources/swaps"
class Medusa {
private client: Client
public auth: AuthResource
public carts: CartsResource
public customers: CustomersResource
public errors: MedusaError
public orders: OrdersResource
public products: ProductsResource
public regions: RegionsResource
public returnReasons: ReturnReasonsResource
public returns: ReturnsResource
public shippingOptions: ShippingOptionsResource
public swaps: SwapsResource
public collections: CollectionsResource
public giftCards: GiftCardsResource
constructor(config: Config) {
this.client = new Client(config)
this.auth = new AuthResource(this.client)
this.carts = new CartsResource(this.client)
this.customers = new CustomersResource(this.client)
this.errors = new MedusaError()
this.orders = new OrdersResource(this.client)
this.products = new ProductsResource(this.client)
this.regions = new RegionsResource(this.client)
this.returnReasons = new ReturnReasonsResource(this.client)
this.returns = new ReturnsResource(this.client)
this.shippingOptions = new ShippingOptionsResource(this.client)
this.swaps = new SwapsResource(this.client)
this.collections = new CollectionsResource(this.client)
this.giftCards = new GiftCardsResource(this.client)
}
}
export default Medusa
+199
View File
@@ -0,0 +1,199 @@
import axios, { AxiosError, AxiosInstance } from "axios"
import * as rax from "retry-axios"
import { v4 as uuidv4 } from "uuid"
export interface Config {
baseUrl: string
maxRetries: number
}
export interface RequestOptions {
apiKey?: string
timeout?: number
numberOfRetries?: number
}
export type RequestMethod = "DELETE" | "POST" | "GET"
const defaultConfig = {
maxRetries: 0,
baseUrl: "http://localhost:9000",
}
class Client {
private axiosClient: AxiosInstance
private config: Config
constructor(config: Config) {
/** @private @constant {AxiosInstance} */
this.axiosClient = this.createClient({ ...defaultConfig, ...config })
/** @private @constant {Config} */
this.config = { ...defaultConfig, ...config }
}
shouldRetryCondition(
err: AxiosError,
numRetries: number,
maxRetries: number
): boolean {
// Obviously, if we have reached max. retries we stop
if (numRetries >= maxRetries) {
return false
}
// If no response, we assume a connection error and retry
if (!err.response) {
return true
}
// Retry on conflicts
if (err.response.status === 409) {
return true
}
// All 5xx errors are retried
// OBS: We are currently not retrying 500 requests, since our core needs proper error handling.
// At the moment, 500 will be returned on all errors, that are not of type MedusaError.
if (err.response.status > 500 && err.response.status <= 599) {
return true
}
return false
}
// Stolen from https://github.com/stripe/stripe-node/blob/fd0a597064289b8c82f374f4747d634050739043/lib/utils.js#L282
normalizeHeaders(obj: object): object {
if (!(obj && typeof obj === "object")) {
return obj
}
return Object.keys(obj).reduce((result, header) => {
result[this.normalizeHeader(header)] = obj[header]
return result
}, {})
}
// Stolen from https://github.com/marten-de-vries/header-case-normalizer/blob/master/index.js#L36-L41
normalizeHeader(header: string): string {
return header
.split("-")
.map(
(text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()
)
.join("-")
}
/**
* Creates all the initial headers.
* We add the idempotency key, if the request is configured to retry.
* @param {object} userHeaders user supplied headers
* @param {Types.RequestMethod} method request method
* @param {string} path request path
* @return {object}
*/
setHeaders(
userHeaders: RequestOptions,
method: RequestMethod,
path: string
): object {
let defaultHeaders: object = {
Accept: "application/json",
"Content-Type": "application/json",
}
// TODO: if route is an authenticated route, add api key
if (path.startsWith("/admin")) {
defaultHeaders = {
...defaultHeaders,
}
}
// only add idempotency key, if we want to retry
if (this.config.maxRetries > 0 && method === "POST") {
defaultHeaders["Idempotency-Key"] = uuidv4()
}
return Object.assign({}, defaultHeaders, this.normalizeHeaders(userHeaders))
}
/**
* Creates the axios client used for requests
* As part of the creation, we configure the retry conditions
* and the exponential backoff approach.
* @param {Config} config user supplied configurations
* @return {AxiosInstance}
*/
createClient(config: Config): AxiosInstance {
const client = axios.create({
baseURL: config.baseUrl,
})
rax.attach(client)
client.defaults.raxConfig = {
instance: client,
retry: config.maxRetries,
backoffType: "exponential",
shouldRetry: (err: AxiosError): boolean => {
const cfg = rax.getConfig(err)
if (cfg) {
return this.shouldRetryCondition(
err,
cfg.currentRetryAttempt || 1,
cfg.retry || 3
)
} else {
return false
}
},
}
return client
}
/**
* Format the response data as:
* { cart: { id: "some_cart", ... } }
* @param {object} data Axios response data
* @param {number} status Axios response status code
* @return {object}
*/
createRawResponse(data: object, status: number): object {
const res = { status }
Object.entries(data).map(([key, value]) => {
res[key] = value
})
return res as any // eslint-disable-line
}
/**
* Axios request
* @param {Types.RequestMethod} method request method
* @param {string} path request path
* @param {object} payload request payload
* @param {RequestOptions} options axios configuration
* @return {object}
*/
async request(
method: RequestMethod,
path: string,
payload: object = {},
options: RequestOptions = {}
): Promise<any> {
const reqOpts = {
method,
withCredentials: true,
url: path,
data: payload,
json: true,
headers: this.setHeaders(options, method, path),
}
const { data, status } = await this.axiosClient(reqOpts)
return this.createRawResponse(data, status)
}
}
export default Client
@@ -0,0 +1,47 @@
import {
StoreCustomersRes,
StorePostCustomersCustomerAddressesAddressReq,
StorePostCustomersCustomerAddressesReq,
} from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import BaseResource from "./base"
class AddressesResource extends BaseResource {
/**
* Adds an address to a customers saved addresses
* @param {StorePostCustomersCustomerAddressesReq} payload contains information to create an address
* @return {AxiosPromise<StoreCustomerResponse>}
*/
addAddress(
payload: StorePostCustomersCustomerAddressesReq
): AxiosPromise<StoreCustomersRes> {
const path = `/store/customers/me/addresses`
return this.client.request("POST", path, payload)
}
/**
* Deletes an address of a customer
* @param {string} address_id id of the address to delete
* @return {AxiosPromise<StoreCustomersResponse>}
*/
deleteAddress(address_id: string): AxiosPromise<StoreCustomersRes> {
const path = `/store/customers/me/addresses/${address_id}`
return this.client.request("DELETE", path)
}
/**
* Update an address of a customer
* @param {string} address_id id of customer
* @param {StorePostCustomersCustomerAddressesAddressReq} payload address update
* @return {StoreCustomersResponse}
*/
updateAddress(
address_id: string,
payload: StorePostCustomersCustomerAddressesAddressReq
): AxiosPromise<StoreCustomersRes> {
const path = `/store/customers/me/addresses/${address_id}`
return this.client.request("POST", path, payload)
}
}
export default AddressesResource
+41
View File
@@ -0,0 +1,41 @@
import { AxiosPromise } from "axios"
import {
StoreGetAuthEmailRes,
StorePostAuthReq,
StoreAuthRes,
} from "@medusajs/medusa"
import BaseResource from "./base"
class AuthResource extends BaseResource {
/**
* @description Authenticates a customer using email and password combination
* @param {StorePostAuthReq} payload authentication payload
* @return {AxiosPromise<StoreAuthRes>}
*/
authenticate(payload: StorePostAuthReq): AxiosPromise<StoreAuthRes> {
const path = `/store/auth`
return this.client.request("POST", path, payload)
}
/**
* @description Retrieves an authenticated session
* Usually used to check if authenticated session is alive.
* @return {AxiosPromise<StoreAuthRes>}
*/
getSession(): AxiosPromise<StoreAuthRes> {
const path = `/store/auth`
return this.client.request("GET", path)
}
/**
* @description Check if email exists
* @param {string} email is required
* @return {AxiosPromise<StoreGetAuthEmailRes>}
*/
exists(email: string): AxiosPromise<StoreGetAuthEmailRes> {
const path = `/store/auth/${email}`
return this.client.request("GET", path)
}
}
export default AuthResource
+9
View File
@@ -0,0 +1,9 @@
import Client from "../request"
export default class BaseResource {
public client: Client
constructor(client: Client) {
this.client = client
}
}
+160
View File
@@ -0,0 +1,160 @@
import {
StoreCartsRes,
StorePostCartReq,
StorePostCartsCartPaymentSessionReq,
StorePostCartsCartPaymentSessionUpdateReq,
StorePostCartsCartReq,
StorePostCartsCartShippingMethodReq,
} from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import BaseResource from "./base"
import LineItemsResource from "./line-items"
class CartsResource extends BaseResource {
public lineItems = new LineItemsResource(this.client)
/**
* Adds a shipping method to cart
* @param {string} cart_id Id of cart
* @param {StorePostCartsCartShippingMethodReq} payload Containg id of shipping option and optional data
* @return {AxiosPromise<StoreCartsRes>}
*/
addShippingMethod(
cart_id: string,
payload: StorePostCartsCartShippingMethodReq
): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/shipping-methods`
return this.client.request("POST", path, payload)
}
/**
* Completes a cart.
* Payment authorization is attempted and if more work is required, we simply return the cart for further updates.
* If payment is authorized and order is not yet created, we make sure to do so.
* The completion of a cart can be performed idempotently with a provided header Idempotency-Key.
* If not provuided, we will generate one for the request.
* @param {string} cart_id is required
* @return {AxiosPromise<StoreCartsRes>}
*/
complete(cart_id: string): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/complete`
return this.client.request("POST", path)
}
/**
* Creates a cart
* @param {StorePostCartReq} payload is optional and can contain a region_id and items.
* The cart will contain the payload, if provided. Otherwise it will be empty
* @return {AxiosPromise<StoreCartsRes>}
*/
create(payload?: StorePostCartReq): AxiosPromise<StoreCartsRes> {
const path = `/store/carts`
return this.client.request("POST", path, payload)
}
/**
* Creates payment sessions.
* Initializes the payment sessions that can be used to pay for the items of the cart.
* This is usually called when a customer proceeds to checkout.
* @param {string} cart_id is required
* @return {AxiosPromise<StoreCartsRes>}
*/
createPaymentSessions(cart_id: string): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/payment-sessions`
return this.client.request("POST", path)
}
/**
* Removes a discount from cart.
* @param {string} cart_id is required
* @param {string} code discount code to remove
* @return {AxiosPromise<StoreCartsRes>}
*/
deleteDiscount(cart_id: string, code: string): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/discounts/${code}`
return this.client.request("DELETE", path)
}
/**
* Removes a payment session from a cart.
* Can be useful in case a payment has failed
* @param {string} cart_id is required
* @param {string} provider_id the provider id of the session e.g. "stripe"
* @return {AxiosPromise<StoreCartsRes>}
*/
deletePaymentSession(
cart_id: string,
provider_id: string
): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/payment-sessions/${provider_id}`
return this.client.request("DELETE", path)
}
/**
* Refreshes a payment session.
* @param {string} cart_id is required
* @param {string} provider_id the provider id of the session e.g. "stripe"
* @return {AxiosPromise<StoreCartsRes>}
*/
refreshPaymentSession(
cart_id: string,
provider_id: string
): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/payment-sessions/${provider_id}/refresh`
return this.client.request("POST", path)
}
/**
* Retrieves a cart
* @param {string} cart_id is required
* @return {AxiosPromise<StoreCartsRes>}
*/
retrieve(cart_id: string): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}`
return this.client.request("GET", path)
}
/**
* Refreshes a payment session.
* @param {string} cart_id is required
* @param {StorePostCartsCartPaymentSessionReq} payload the provider id of the session e.g. "stripe"
* @return {AxiosPromise<StoreCartsRes>}
*/
setPaymentSession(
cart_id: string,
payload: StorePostCartsCartPaymentSessionReq
): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/payment-session`
return this.client.request("POST", path, payload)
}
/**
* Updates a cart
* @param {string} cart_id is required
* @param {StorePostCartsCartReq} payload is required and can contain region_id, email, billing and shipping address
* @return {AxiosPromise<StoreCartsRes>}
*/
update(
cart_id: string,
payload: StorePostCartsCartReq
): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}`
return this.client.request("POST", path, payload)
}
/**
* Updates the payment method
* @param {string} cart_id is required
* @param {StorePostCartsCartPaymentSessionUpdateReq} payload is required
* @return {AxiosPromise<StoreCartsRes>}
*/
updatePaymentSession(
cart_id: string,
payload: StorePostCartsCartPaymentSessionUpdateReq
): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/payment-session/update`
return this.client.request("POST", path, payload)
}
}
export default CartsResource
@@ -0,0 +1,42 @@
import { AxiosPromise } from "axios"
import {
StoreCollectionsRes,
StoreCollectionsListRes,
StoreGetCollectionsParams,
} from "@medusajs/medusa"
import BaseResource from "./base"
class CollectionsResource extends BaseResource {
/**
* @description Retrieves a single collection
* @param {string} id id of the collection
* @return {AxiosPromise<StoreCollectionsRes>}
*/
retrieve(id: string): AxiosPromise<StoreCollectionsRes> {
const path = `/store/collections/${id}`
return this.client.request("GET", path)
}
/**
* @description Retrieves a list of collections
* @param {string} query is optional. Can contain a limit and offset for the returned list
* @return {AxiosPromise<StoreCollectionsListRes>}
*/
list(
query?: StoreGetCollectionsParams
): AxiosPromise<StoreCollectionsListRes> {
let path = `/store/collections`
if (query) {
const queryString = Object.entries(query).map(([key, value]) => {
return `${key}=${value}`
})
path = `/store/collections?${queryString.join("&")}`
}
return this.client.request("GET", path)
}
}
export default CollectionsResource
@@ -0,0 +1,102 @@
import {
StoreCustomersListOrdersRes,
StoreCustomersRes,
StoreGetCustomersCustomerOrdersParams,
StorePostCustomersCustomerPasswordTokenReq,
StorePostCustomersCustomerReq,
StorePostCustomersReq,
} from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import AddressesResource from "./addresses"
import BaseResource from "./base"
import PaymentMethodsResource from "./payment-methods"
class CustomerResource extends BaseResource {
public paymentMethods = new PaymentMethodsResource(this.client)
public addresses = new AddressesResource(this.client)
/**
* Creates a customer
* @param {StorePostCustomersReq} payload information of customer
* @return { AxiosPromise<StoreCustomersRes>}
*/
create(payload: StorePostCustomersReq): AxiosPromise<StoreCustomersRes> {
const path = `/store/customers`
return this.client.request("POST", path, payload)
}
/**
* Retrieves the customer that is currently logged
* @return {AxiosPromise<StoreCustomersRes>}
*/
retrieve(): AxiosPromise<StoreCustomersRes> {
const path = `/store/customers/me`
return this.client.request("GET", path)
}
/**
* Updates a customer
* @param {StorePostCustomersCustomerReq} payload information to update customer with
* @return {AxiosPromise<StoreCustomersRes>}
*/
update(
payload: StorePostCustomersCustomerReq
): AxiosPromise<StoreCustomersRes> {
const path = `/store/customers/me`
return this.client.request("POST", path, payload)
}
/**
* Retrieve customer orders
* @param {StoreGetCustomersCustomerOrdersParams} params optional params to retrieve orders
* @return {AxiosPromise<StoreCustomersListOrdersRes>}
*/
listOrders(
params?: StoreGetCustomersCustomerOrdersParams
): AxiosPromise<StoreCustomersListOrdersRes> {
let path = `/store/customers/me/orders`
if (params) {
let query: string | undefined
for (const key of Object.keys(params)) {
if (query) {
query += `&${key}=${params[key]}`
} else {
query = `?${key}=${params[key]}`
}
}
if (query) {
path += query
}
}
return this.client.request("GET", path)
}
/**
* Resets customer password
* @param {StorePostCustomersCustomerPasswordTokenReq} payload info used to reset customer password
* @return {AxiosPromise<StoreCustomersRes>}
*/
resetPassword(
payload: StorePostCustomersCustomerPasswordTokenReq
): AxiosPromise<StoreCustomersRes> {
const path = `/store/customers/password-reset`
return this.client.request("POST", path, payload)
}
/**
* Generates a reset password token, which can be used to reset the password.
* The token is not returned but should be sent out to the customer in an email.
* @param {StorePostCustomersCustomerPasswordTokenReq} payload info used to generate token
* @return {AxiosPromise}
*/
generatePasswordToken(
payload: StorePostCustomersCustomerPasswordTokenReq
): AxiosPromise {
const path = `/store/customers/password-token`
return this.client.request("POST", path, payload)
}
}
export default CustomerResource
@@ -0,0 +1,17 @@
import { StoreGiftCardsRes } from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import BaseResource from "./base"
class GiftCardsResource extends BaseResource {
/**
* @description Retrieves a single GiftCard
* @param {string} code code of the gift card
* @return {AxiosPromise<StoreGiftCardsRes>}
*/
retrieve(code: string): AxiosPromise<StoreGiftCardsRes> {
const path = `/store/gift-cards/${code}`
return this.client.request("GET", path)
}
}
export default GiftCardsResource
@@ -0,0 +1,54 @@
import {
StoreCartsRes,
StoreCartsDeleteRes,
StorePostCartsCartLineItemsItemReq,
StorePostCartsCartLineItemsReq,
} from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import BaseResource from "./base"
class LineItemsResource extends BaseResource {
/**
* Creates a line-item for a cart
* @param {string} cart_id id of cart
* @param {StorePostCartsCartLineItemsReq} payload details needed to create a line-item
* @return {AxiosPromise<StoreCartsCartRes>}
*/
create(
cart_id: string,
payload: StorePostCartsCartLineItemsReq
): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/line-items`
return this.client.request("POST", path, payload)
}
/**
* Updates a line-item.
* Only quantity updates are allowed
* @param {string} cart_id id of cart
* @param {string} line_id id of item to update
* @param {StorePostCartsCartLineItemsItemReq} payload details needed to update a line-item
* @return {AxiosPromise<StoreCartsCartRes>}
*/
update(
cart_id: string,
line_id: string,
payload: StorePostCartsCartLineItemsItemReq
): AxiosPromise<StoreCartsRes> {
const path = `/store/carts/${cart_id}/line-items/${line_id}`
return this.client.request("POST", path, payload)
}
/**
* Remove a line-item from a cart
* @param {string} cart_id id of cart
* @param {string} line_id id of item to remove
* @return {AxiosPromise<StoreCartsDeleteRes>}
*/
delete(cart_id: string, line_id: string): AxiosPromise<StoreCartsDeleteRes> {
const path = `/store/carts/${cart_id}/line-items/${line_id}`
return this.client.request("DELETE", path)
}
}
export default LineItemsResource
@@ -0,0 +1,48 @@
import { StoreGetOrdersParams, StoreOrdersRes } from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import BaseResource from "./base"
class OrdersResource extends BaseResource {
/**
* @description Retrieves an order
* @param {string} id is required
* @return {AxiosPromise<StoreOrdersRes>}
*/
retrieve(id: string): AxiosPromise<StoreOrdersRes> {
const path = `/store/orders/${id}`
return this.client.request("GET", path)
}
/**
* @description Retrieves an order by cart id
* @param {string} cart_id is required
* @return {AxiosPromise<StoreOrdersRes>}
*/
retrieveByCartId(cart_id: string): AxiosPromise<StoreOrdersRes> {
const path = `/store/orders/cart/${cart_id}`
return this.client.request("GET", path)
}
/**
* @description Look up an order using order details
* @param {StoreGetOrdersParams} payload details used to look up the order
* @return {AxiosPromise<StoreOrdersRes>}
*/
lookupOrder(payload: StoreGetOrdersParams): AxiosPromise<StoreOrdersRes> {
let path = `/store/orders?`
const queryString = Object.entries(payload).map(([key, value]) => {
let val = value
if (Array.isArray(value)) {
val = value.join(",")
}
return `${key}=${encodeURIComponent(val as string)}`
})
path = `/store/orders?${queryString.join("&")}`
return this.client.request("GET", path, payload)
}
}
export default OrdersResource
@@ -0,0 +1,16 @@
import BaseResource from "./base"
import { AxiosPromise } from "axios"
class PaymentMethodsResource extends BaseResource {
/**
* Lists customer payment methods
* @param {string} id id of cart
* @return {AxiosPromise<{ payment_methods: object[] }>}
*/
list(id: string): AxiosPromise<{ payment_methods: object[] }> {
const path = `/store/carts/${id}/payment-methods`
return this.client.request("GET", path)
}
}
export default PaymentMethodsResource
@@ -0,0 +1,43 @@
import {
StoreGetVariantsParams,
StoreVariantsListRes,
StoreVariantsRes,
} from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import BaseResource from "./base"
class ProductVariantsResource extends BaseResource {
/**
* @description Retrieves a single product variant
* @param {string} id is required
* @return {AxiosPromise<StoreVariantsRes>}
*/
retrieve(id: string): AxiosPromise<StoreVariantsRes> {
const path = `/store/variants/${id}`
return this.client.request("GET", path)
}
/**
* @description Retrieves a list of of Product Variants
* @param {StoreVariantsListParamsObject} query
* @return {AxiosPromise<StoreVariantsListRes>}
*/
list(query?: StoreGetVariantsParams): AxiosPromise<StoreVariantsListRes> {
const path = `/store/variants`
const search = Object.entries(query || {}).map(([key, value]) => {
if (Array.isArray(value)) {
return `${key}=${value.join(",")}`
}
return `${key}=${value}`
})
return this.client.request(
"GET",
`${path}${search.length > 0 && `?${search.join("&")}`}`
)
}
}
export default ProductVariantsResource
@@ -0,0 +1,55 @@
import {
StoreGetProductsParams,
StorePostSearchReq,
StorePostSearchRes,
StoreProductsListRes,
StoreProductsRes,
} from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import BaseResource from "./base"
import ProductVariantsResource from "./product-variants"
class ProductsResource extends BaseResource {
public variants = new ProductVariantsResource(this.client)
/**
* @description Retrieves a single Product
* @param {string} id is required
* @return {AxiosPromise<StoreProductsRes>}
*/
retrieve(id: string): AxiosPromise<StoreProductsRes> {
const path = `/store/products/${id}`
return this.client.request("GET", path)
}
/**
* @description Searches for products
* @param {StorePostSearchReq} searchOptions is required
* @return {AxiosPromise<StorePostSearchRes>}
*/
search(searchOptions: StorePostSearchReq): AxiosPromise<StorePostSearchRes> {
const path = `/store/products/search`
return this.client.request("POST", path, searchOptions)
}
/**
* @description Retrieves a list of products
* @param {StoreGetProductsParams} query is optional. Can contain a limit and offset for the returned list
* @return {AxiosPromise<StoreProductsListRes>}
*/
list(query?: StoreGetProductsParams): AxiosPromise<StoreProductsListRes> {
let path = `/store/products`
if (query) {
const queryString = Object.entries(query).map(([key, value]) => {
return `${key}=${value}`
})
path = `/store/products?${queryString.join("&")}`
}
return this.client.request("GET", path)
}
}
export default ProductsResource
@@ -0,0 +1,26 @@
import { AxiosPromise } from "axios"
import { StoreRegionsListRes, StoreRegionsRes } from "@medusajs/medusa"
import BaseResource from "./base"
class RegionsResource extends BaseResource {
/**
* @description Retrieves a list of regions
* @return {AxiosPromise<StoreRegionsListRes>}
*/
list(): AxiosPromise<StoreRegionsListRes> {
const path = `/store/regions`
return this.client.request("GET", path)
}
/**
* @description Retrieves a region
* @param {string} id is required
* @return {AxiosPromise<StoreRegionsRes>}
*/
retrieve(id: string): AxiosPromise<StoreRegionsRes> {
const path = `/store/regions/${id}`
return this.client.request("GET", path)
}
}
export default RegionsResource
@@ -0,0 +1,29 @@
import BaseResource from "./base"
import {
StoreReturnReasonsListRes,
StoreReturnReasonsRes,
} from "@medusajs/medusa"
import { AxiosPromise } from "axios"
class ReturnReasonsResource extends BaseResource {
/**
* @description Retrieves a single Return Reason
* @param {string} id is required
* @return {AxiosPromise<StoreReturnReasonsRes>}
*/
retrieve(id: string): AxiosPromise<StoreReturnReasonsRes> {
const path = `/store/return-reasons/${id}`
return this.client.request("GET", path)
}
/**
* Lists return reasons defined in Medusa Admin
* @return {AxiosPromise<StoreReturnReasonsListRes>}
*/
list(): AxiosPromise<StoreReturnReasonsListRes> {
const path = `/store/return-reasons`
return this.client.request("GET", path)
}
}
export default ReturnReasonsResource
@@ -0,0 +1,17 @@
import BaseResource from "./base"
import { AxiosPromise } from "axios"
import { StoreReturnsRes, StorePostReturnsReq } from "@medusajs/medusa"
class ReturnsResource extends BaseResource {
/**
* Creates a return request
* @param {StorePostReturnsReq} payload details needed to create a return
* @return {AxiosPromise<StoreReturnsRes>}
*/
create(payload: StorePostReturnsReq): AxiosPromise<StoreReturnsRes> {
const path = `/store/returns`
return this.client.request("POST", path, payload)
}
}
export default ReturnsResource
@@ -0,0 +1,44 @@
import {
StoreGetShippingOptionsParams,
StoreShippingOptionsListRes,
} from "@medusajs/medusa"
import { AxiosPromise } from "axios"
import BaseResource from "./base"
class ShippingOptionsResource extends BaseResource {
/**
* @description Lists shiping options available for a cart
* @param {string} cart_id
* @return {AxiosPromise<StoreShippingOptionsListRes>}
*/
listCartOptions(cart_id: string): AxiosPromise<StoreShippingOptionsListRes> {
const path = `/store/shipping-options/${cart_id}`
return this.client.request("GET", path)
}
/**
* @description Lists shiping options available
* @param {StoreGetShippingOptionsParamsObject} query
* @return {AxiosPromise<StoreShippingOptionsListRes>}
*/
list(
query?: StoreGetShippingOptionsParams
): AxiosPromise<StoreShippingOptionsListRes> {
let path = `/store/shipping-options`
const queryString = Object.entries(query || {}).map(([key, value]) => {
let val = value
if (Array.isArray(value)) {
val = value.join(",")
}
return `${key}=${val}`
})
path = `/store/shipping-options?${queryString.join("&")}`
return this.client.request("GET", path)
}
}
export default ShippingOptionsResource
+27
View File
@@ -0,0 +1,27 @@
import { AxiosPromise } from "axios"
import { StoreSwapsRes, StorePostSwapsReq } from "@medusajs/medusa"
import BaseResource from "./base"
class SwapsResource extends BaseResource {
/**
* @description Creates a swap from a cart
* @param {StorePostSwapsReq} payload
* @return {AxiosPromise<StoreSwapsRes>}
*/
create(payload: StorePostSwapsReq): AxiosPromise<StoreSwapsRes> {
const path = `/store/swaps`
return this.client.request("POST", path, payload)
}
/**
* @description Retrieves a swap by cart id
* @param {string} cart_id id of cart
* @return {AxiosPromise<StoreSwapsRes>}
*/
retrieveByCartId(cart_id: string): AxiosPromise<StoreSwapsRes> {
const path = `/store/swaps/${cart_id}`
return this.client.request("GET", path)
}
}
export default SwapsResource
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"lib": ["es5", "es6"],
"target": "es5",
"outDir": "./dist",
"esModuleInterop": true,
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"noImplicitReturns": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"allowJs": true,
"skipLibCheck": true
},
"include": ["src"],
"exclude": ["node_modules", " **/tests/*"]
}
File diff suppressed because it is too large Load Diff
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.33](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.32...medusa-payment-adyen@1.1.33) (2021-11-19)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.32](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.31...medusa-payment-adyen@1.1.32) (2021-11-19)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.31](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.30...medusa-payment-adyen@1.1.31) (2021-10-18)
**Note:** Version bump only for package medusa-payment-adyen
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-adyen",
"version": "1.1.31",
"version": "1.1.33",
"description": "Adyen Payment provider for Medusa Commerce",
"main": "index.js",
"repository": {
@@ -24,7 +24,7 @@
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.29"
"medusa-test-utils": "^1.1.31"
},
"scripts": {
"build": "babel src -d .",
@@ -42,7 +42,7 @@
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26"
"medusa-core-utils": "^1.1.28"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.33](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.32...medusa-payment-klarna@1.1.33) (2021-11-19)
**Note:** Version bump only for package medusa-payment-klarna
## [1.1.32](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.31...medusa-payment-klarna@1.1.32) (2021-11-19)
**Note:** Version bump only for package medusa-payment-klarna
## [1.1.31](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.30...medusa-payment-klarna@1.1.31) (2021-10-18)
**Note:** Version bump only for package medusa-payment-klarna
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-klarna",
"version": "1.1.31",
"version": "1.1.33",
"description": "Klarna Payment provider for Medusa Commerce",
"main": "index.js",
"repository": {
@@ -40,8 +40,8 @@
"axios": "^0.21.0",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26",
"medusa-test-utils": "^1.1.29"
"medusa-core-utils": "^1.1.28",
"medusa-test-utils": "^1.1.31"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.0.10](https://github.com/medusajs/medusa/compare/medusa-payment-manual@1.0.9...medusa-payment-manual@1.0.10) (2021-11-19)
**Note:** Version bump only for package medusa-payment-manual
## [1.0.9](https://github.com/medusajs/medusa/compare/medusa-payment-manual@1.0.8...medusa-payment-manual@1.0.9) (2021-11-19)
**Note:** Version bump only for package medusa-payment-manual
## [1.0.8](https://github.com/medusajs/medusa/compare/medusa-payment-manual@1.0.7...medusa-payment-manual@1.0.8) (2021-10-18)
**Note:** Version bump only for package medusa-payment-manual
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-manual",
"version": "1.0.8",
"version": "1.0.10",
"description": "A dummy payment provider to be used for testing or manual payments",
"main": "index.js",
"repository": {
@@ -25,7 +25,7 @@
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.29"
"medusa-test-utils": "^1.1.31"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__",
@@ -36,5 +36,5 @@
"peerDependencies": {
"medusa-interfaces": "1.x"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
+5 -3
View File
@@ -3,11 +3,13 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.0.31](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.30...medusa-payment-paypal@1.0.31) (2021-11-11)
## [1.0.32](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.30...medusa-payment-paypal@1.0.32) (2021-11-19)
### Bug Fixes
**Note:** Version bump only for package medusa-payment-paypal
- account for lowest currency unit in paypal ([#761](https://github.com/medusajs/medusa/issues/761)) ([b30a2af](https://github.com/medusajs/medusa/commit/b30a2af94de32476d82bbe4727ee7b224d6437fe))
## [1.0.31](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.30...medusa-payment-paypal@1.0.31) (2021-11-19)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.30](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.29...medusa-payment-paypal@1.0.30) (2021-10-18)
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-paypal",
"version": "1.0.31",
"version": "1.0.32",
"description": "Paypal Payment provider for Meduas Commerce",
"main": "index.js",
"repository": {
@@ -26,8 +26,8 @@
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-interfaces": "^1.1.27",
"medusa-test-utils": "^1.1.29"
"medusa-interfaces": "^1.1.29",
"medusa-test-utils": "^1.1.31"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__,**/__mocks__",
@@ -42,7 +42,7 @@
"@paypal/checkout-server-sdk": "^1.0.2",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26"
"medusa-core-utils": "^1.1.28"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
}
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.32](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.31...medusa-payment-stripe@1.1.32) (2021-11-19)
**Note:** Version bump only for package medusa-payment-stripe
## [1.1.31](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.30...medusa-payment-stripe@1.1.31) (2021-11-19)
**Note:** Version bump only for package medusa-payment-stripe
## [1.1.30](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.29...medusa-payment-stripe@1.1.30) (2021-10-18)
**Note:** Version bump only for package medusa-payment-stripe
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-stripe",
"version": "1.1.30",
"version": "1.1.32",
"description": "Stripe Payment provider for Meduas Commerce",
"main": "index.js",
"repository": {
@@ -26,7 +26,7 @@
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.29"
"medusa-test-utils": "^1.1.31"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__",
@@ -40,8 +40,8 @@
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26",
"medusa-core-utils": "^1.1.28",
"stripe": "^8.50.0"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
@@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.31](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.30...medusa-plugin-add-ons@1.1.31) (2021-11-19)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.30](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.29...medusa-plugin-add-ons@1.1.30) (2021-11-19)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.29](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.28...medusa-plugin-add-ons@1.1.29) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-add-ons
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-add-ons",
"version": "1.1.29",
"version": "1.1.31",
"description": "Add-on plugin for Medusa Commerce",
"main": "index.js",
"repository": {
@@ -25,7 +25,7 @@
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.29"
"medusa-test-utils": "^1.1.31"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__",
@@ -37,8 +37,8 @@
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.26",
"medusa-core-utils": "^1.1.28",
"redis": "^3.0.2"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
"gitHead": "a69b1e85be1da3b1b5bc4c5446471252623c8808"
}
+15
View File
@@ -0,0 +1,15 @@
/dist
.env
.DS_Store
/uploads
/node_modules
yarn-error.log
/dist
/api
/services
/models
/subscribers
/loaders
/utils
+13
View File
@@ -0,0 +1,13 @@
/lib
node_modules
.DS_store
.env*
/*.js
!index.js
yarn.lock
src
.gitignore
.eslintrc
.babelrc
.prettierrc
@@ -0,0 +1,15 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [0.0.3](https://github.com/medusajs/medusa/compare/medusa-plugin-algolia@0.0.2...medusa-plugin-algolia@0.0.3) (2021-11-19)
**Note:** Version bump only for package medusa-plugin-algolia
## 0.0.2 (2021-11-19)
### Features
- Algolia plugin for medusa ([#718](https://github.com/medusajs/medusa/issues/718)) ([8ce9b20](https://github.com/medusajs/medusa/commit/8ce9b20222e1f4db75f730898549f0ed09eb1574))
- Typescript for API layer ([#817](https://github.com/medusajs/medusa/issues/817)) ([373532e](https://github.com/medusajs/medusa/commit/373532ecbc8196f47e71af95a8cf82a14a4b1f9e))
+20
View File
@@ -0,0 +1,20 @@
# medusa-plugin-algolia
algolia Plugin for Medusa to search for products.
## Plugin Options
```
{
application_id: "someId",
admin_api_key: "someApiKey",
settings: {
[indexName]: [algolia settings passed to algolia's `updateSettings()` method]
// example
products: {
searchableAttributes: ["title", "description", "variant_sku", "type_value"],
attributesToRetrieve: ["title", "description", "variant_sku", "type_value"],
}
}
}
```
+1
View File
@@ -0,0 +1 @@
//noop
@@ -0,0 +1,3 @@
module.exports = {
testEnvironment: "node",
}
@@ -0,0 +1,46 @@
{
"name": "medusa-plugin-algolia",
"version": "0.0.3",
"description": "Search support for algolia",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/medusa-plugin-algolia"
},
"author": "rolwin100",
"license": "MIT",
"scripts": {
"build": "babel src -d .",
"prepare": "cross-env NODE_ENV=production npm run build",
"watch": "babel -w src --out-dir . --ignore **/__tests__",
"test": "jest"
},
"peerDependencies": {
"medusa-interfaces": "1.x",
"typeorm": "0.x"
},
"dependencies": {
"algoliasearch": "^4.10.5",
"body-parser": "^1.19.0",
"lodash": "^4.17.21",
"medusa-core-utils": "^1.1.28",
"medusa-interfaces": "^1.1.29"
},
"devDependencies": {
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/node": "^7.7.4",
"@babel/plugin-proposal-class-properties": "^7.7.4",
"@babel/plugin-transform-instanceof": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.7.6",
"@babel/preset-env": "^7.7.5",
"@babel/register": "^7.7.4",
"@babel/runtime": "^7.9.6",
"client-sessions": "^0.8.0",
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2"
},
"gitHead": "aa460f63591f9625f1fe98749b34172e528bed7f"
}

Some files were not shown because too many files have changed in this diff Show More