chore(medusa): Typeorm upgrade to 0.3.11 (#3041)

This commit is contained in:
Riqwan Thamir authored and GitHub committed 2023-02-15 16:25:30 +01:00
1 parent 8137061908
commit 121b42acfe
275 files changed
+4493 -4780

No files matched your search

@@ -470,7 +470,7 @@ describe("/admin/order-edits", () => {
withDeleted: true,
})
expect(orderEdit).toBeUndefined()
expect(orderEdit).toBeNull()
expect(response.status).toEqual(200)
expect(response.data).toEqual({
id,
@@ -534,7 +534,7 @@ describe("/admin/order-edits", () => {
withDeleted: true,
})
expect(orderEdit).toBeUndefined()
expect(orderEdit).toBeNull()
expect(response.status).toEqual(200)
expect(response.data).toEqual({
id: orderEditId,
@@ -2123,7 +2123,9 @@ describe("/admin/orders", () => {
const manager = dbConnection.manager
const customOptions = await manager.find(CustomShippingOption, {
shipping_option_id: "test-option",
where: {
shipping_option_id: "test-option",
},
})
expect(response.status).toEqual(200)
@@ -23,7 +23,7 @@ const adminReqConfig = {
},
}
jest.setTimeout(30000)
jest.setTimeout(50000)
describe("/admin/price-lists", () => {
let medusaProcess
@@ -1108,52 +1108,66 @@ describe("/admin/price-lists", () => {
expect(response.status).toEqual(200)
expect(response.data.count).toEqual(2)
expect(response.data.products).toHaveLength(2)
expect(response.data.products).toEqual([
expect.objectContaining({
id: "test-prod-2",
variants: expect.arrayContaining([
expect.objectContaining({
id: "test-variant-3",
prices: expect.arrayContaining([
expect.objectContaining({ currency_code: "usd", amount: 100 }),
]),
}),
expect.objectContaining({
id: "test-variant-4",
prices: expect.arrayContaining([
expect.objectContaining({ currency_code: "usd", amount: 100 }),
expect.objectContaining({
currency_code: "usd",
amount: 150,
price_list_id: "test-list",
}),
]),
}),
]),
}),
expect.objectContaining({
id: "test-prod-1",
variants: expect.arrayContaining([
expect.objectContaining({
id: "test-variant-1",
prices: expect.arrayContaining([
expect.objectContaining({ currency_code: "usd", amount: 100 }),
expect.objectContaining({
currency_code: "usd",
amount: 150,
price_list_id: "test-list",
}),
]),
}),
expect.objectContaining({
id: "test-variant-2",
prices: expect.arrayContaining([
expect.objectContaining({ currency_code: "usd", amount: 100 }),
]),
}),
]),
}),
])
expect(response.data.products).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: "test-prod-1",
variants: expect.arrayContaining([
expect.objectContaining({
id: "test-variant-1",
prices: expect.arrayContaining([
expect.objectContaining({
currency_code: "usd",
amount: 100,
}),
expect.objectContaining({
currency_code: "usd",
amount: 150,
price_list_id: "test-list",
}),
]),
}),
expect.objectContaining({
id: "test-variant-2",
prices: expect.arrayContaining([
expect.objectContaining({
currency_code: "usd",
amount: 100,
}),
]),
}),
]),
}),
expect.objectContaining({
id: "test-prod-2",
variants: expect.arrayContaining([
expect.objectContaining({
id: "test-variant-3",
prices: expect.arrayContaining([
expect.objectContaining({
currency_code: "usd",
amount: 100,
}),
]),
}),
expect.objectContaining({
id: "test-variant-4",
prices: expect.arrayContaining([
expect.objectContaining({
currency_code: "usd",
amount: 100,
}),
expect.objectContaining({
currency_code: "usd",
amount: 150,
price_list_id: "test-list",
}),
]),
}),
]),
}),
])
)
})
it("lists only product 2", async () => {
@@ -2142,7 +2142,6 @@ describe("/admin/products", () => {
const variant = response.data.product.variants.find(
(v) => v.id === variantId
)
expect(variant.prices.length).toEqual(data.prices.length)
expect(variant.prices).toEqual(
@@ -2467,10 +2466,10 @@ describe("/admin/products", () => {
const api = useApi()
const variantPre = await dbConnection.manager.findOne(ProductVariant, {
id: "test-variant",
where: { id: "test-variant" },
})
expect(variantPre).not.toEqual(undefined)
expect(variantPre).toBeTruthy()
const response = await api
.delete("/admin/products/test-product", adminHeaders)
@@ -2488,10 +2487,10 @@ describe("/admin/products", () => {
)
const variant = await dbConnection.manager.findOne(ProductVariant, {
id: "test-variant",
where: { id: "test-variant" },
})
expect(variant).toEqual(undefined)
expect(variant).not.toBeTruthy()
})
it("successfully deletes a product variant and its associated option values", async () => {
@@ -2499,10 +2498,10 @@ describe("/admin/products", () => {
// Validate that the option value exists
const optValPre = await dbConnection.manager.findOne(ProductOptionValue, {
variant_id: "test-variant_2",
where: { variant_id: "test-variant_2" },
})
expect(optValPre).not.toEqual(undefined)
expect(optValPre).toBeTruthy()
// Soft delete the variant
const response = await api.delete(
@@ -2515,20 +2514,18 @@ describe("/admin/products", () => {
// Validate that the option value was deleted
const optValPost = await dbConnection.manager.findOne(
ProductOptionValue,
{
variant_id: "test-variant_2",
}
{ where: { variant_id: "test-variant_2" } }
)
expect(optValPost).toEqual(undefined)
expect(optValPost).not.toBeTruthy()
// Validate that the option still exists in the DB with deleted_at
const optValDeleted = await dbConnection.manager.findOne(
ProductOptionValue,
{
variant_id: "test-variant_2",
},
{
where: {
variant_id: "test-variant_2",
},
withDeleted: true,
}
)
@@ -2546,10 +2543,10 @@ describe("/admin/products", () => {
// Validate that the option value exists
const optValPre = await dbConnection.manager.findOne(ProductOptionValue, {
variant_id: "test-variant_2",
where: { variant_id: "test-variant_2" },
})
expect(optValPre).not.toEqual(undefined)
expect(optValPre).toBeTruthy()
// Soft delete the product
const response = await api.delete(
@@ -2563,19 +2560,19 @@ describe("/admin/products", () => {
const optValPost = await dbConnection.manager.findOne(
ProductOptionValue,
{
variant_id: "test-variant_2",
where: { variant_id: "test-variant_2" },
}
)
expect(optValPost).toEqual(undefined)
expect(optValPost).not.toBeTruthy()
// Validate that the option still exists in the DB with deleted_at
const optValDeleted = await dbConnection.manager.findOne(
ProductOptionValue,
{
variant_id: "test-variant_2",
},
{
where: {
variant_id: "test-variant_2",
},
withDeleted: true,
}
)
@@ -2593,10 +2590,10 @@ describe("/admin/products", () => {
// Validate that the price exists
const pricePre = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
where: { id: "test-price" },
})
expect(pricePre).not.toEqual(undefined)
expect(pricePre).toBeTruthy()
// Soft delete the variant
const response = await api.delete(
@@ -2608,21 +2605,18 @@ describe("/admin/products", () => {
// Validate that the price was deleted
const pricePost = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
where: { id: "test-price" },
})
expect(pricePost).toEqual(undefined)
expect(pricePost).not.toBeTruthy()
// Validate that the price still exists in the DB with deleted_at
const optValDeleted = await dbConnection.manager.findOne(
MoneyAmount,
{
const optValDeleted = await dbConnection.manager.findOne(MoneyAmount, {
where: {
id: "test-price",
},
{
withDeleted: true,
}
)
withDeleted: true,
})
expect(optValDeleted).toEqual(
expect.objectContaining({
@@ -2637,10 +2631,10 @@ describe("/admin/products", () => {
// Validate that the price exists
const pricePre = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
where: { id: "test-price" },
})
expect(pricePre).not.toEqual(undefined)
expect(pricePre).toBeTruthy()
// Soft delete the product
const response = await api.delete(
@@ -2652,21 +2646,18 @@ describe("/admin/products", () => {
// Validate that the price has been deleted
const pricePost = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
where: { id: "test-price" },
})
expect(pricePost).toEqual(undefined)
expect(pricePost).not.toBeTruthy()
// Validate that the price still exists in the DB with deleted_at
const optValDeleted = await dbConnection.manager.findOne(
MoneyAmount,
{
const optValDeleted = await dbConnection.manager.findOne(MoneyAmount, {
where: {
id: "test-price",
},
{
withDeleted: true,
}
)
withDeleted: true,
})
expect(optValDeleted).toEqual(
expect.objectContaining({
@@ -92,7 +92,7 @@ describe("/admin/shipping-options", () => {
)
})
it("fails as it is not allowed to set id from client side", async () => {
it("fails to add a a requirement with an id if it does not exists", async () => {
const api = useApi()
const payload = {
@@ -123,7 +123,9 @@ describe("/admin/shipping-options", () => {
})
expect(res.status).toEqual(400)
expect(res.data.message).toEqual("ID does not exist")
expect(res.data.message).toEqual(
"Shipping option requirement with id not_allowed does not exist"
)
})
it("it successfully updates a set of existing requirements", async () => {
@@ -274,7 +276,9 @@ describe("/admin/shipping-options", () => {
const manager = dbConnection.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfile.default,
},
})
payload = {
@@ -521,7 +525,9 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] /admin/shipping-options", () => {
const defaultProfile = await dbConnection.manager.findOne(
ShippingProfile,
{
type: "default",
where: {
type: ShippingProfile.default,
},
}
)
@@ -75,7 +75,9 @@ describe("/admin/store", () => {
medusaProcess = await setupServer({ cwd })
const manager = dbConnection.manager
const store = await manager.findOne(Store, { name: "Medusa Store" })
const store = await manager.findOne(Store, {
where: { name: "Medusa Store" },
})
await manager.query(
`INSERT INTO store_currencies (store_id, currency_code) VALUES ('${store.id}', 'dkk')`
)
@@ -59,6 +59,7 @@ Object {
"title": "Test variant",
"upc": "test-upc",
"updated_at": Any<String>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -150,6 +151,7 @@ Object {
"title": "Test variant",
"upc": "test-upc",
"updated_at": Any<String>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -216,6 +218,7 @@ Object {
"title": "test2",
"upc": null,
"updated_at": Any<String>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -314,6 +317,7 @@ Object {
"title": "Test variant",
"upc": "test-upc",
"updated_at": Any<String>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -380,6 +384,7 @@ Object {
"title": "Test variant",
"upc": "test-upc",
"updated_at": Any<String>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -52,7 +52,9 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] Gift Card - Tax calculations", () =>
includes_tax: true,
})
customer = await simpleCustomerFactory(dbConnection, { password: 'medusatest' })
customer = await simpleCustomerFactory(dbConnection, {
password: "medusatest",
})
customerData = {
email: customer.email,
password: "medusatest",
@@ -64,15 +66,19 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] Gift Card - Tax calculations", () =>
is_giftcard: true,
discountable: false,
options: [{ id: "denom", title: "Denomination" }],
variants: [{
title: "Gift Card",
prices: [{
amount: 30000,
currency: "usd",
region_id: region.id,
}],
options: [{ option_id: "denom", value: "Denomination" }],
}]
variants: [
{
title: "Gift Card",
prices: [
{
amount: 30000,
currency: "usd",
region_id: region.id,
},
],
options: [{ option_id: "denom", value: "Denomination" }],
},
],
})
})
@@ -84,10 +90,12 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] Gift Card - Tax calculations", () =>
const createCartRes = await api.post("/store/carts", {
region_id: region.id,
items: [{
variant_id: product.variants[0].id,
quantity: 1,
}],
items: [
{
variant_id: product.variants[0].id,
quantity: 1,
},
],
})
expect(createCartRes.status).toEqual(200)
@@ -112,8 +120,8 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] Gift Card - Tax calculations", () =>
id: product.variants[0].id,
product: expect.objectContaining({
is_giftcard: true,
})
})
}),
}),
}),
])
)
@@ -142,10 +150,12 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] Gift Card - Tax calculations", () =>
const getCartResponse = await api.get(`/store/carts/${cartFactory.id}`)
const cart = getCartResponse.data.cart
await api.post(`/store/carts/${cart.id}/payment-sessions`)
const createdOrder = await api.post(`/store/carts/${cart.id}/complete-cart`)
const createdOrder = await api.post(
`/store/carts/${cart.id}/complete-cart`
)
const createdGiftCards = await dbConnection.manager.find(GiftCard, {
where: { order_id: createdOrder.data.data.id }
where: { order_id: createdOrder.data.data.id },
})
const createdGiftCard = createdGiftCards[0]
@@ -166,14 +176,18 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] Gift Card - Tax calculations", () =>
tax_rate: region.tax_rate,
})
const expensiveProduct = await simpleProductFactory(dbConnection, {
variants: [{
title: "Product cost higher than gift card balance",
prices: [{
amount: 50000,
currency: "usd",
region_id: region.id,
}],
}]
variants: [
{
title: "Product cost higher than gift card balance",
prices: [
{
amount: 50000,
currency: "usd",
region_id: region.id,
},
],
},
],
})
const customerRes = await api.post("/store/customers", customerData, {
@@ -203,7 +217,9 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] Gift Card - Tax calculations", () =>
const getCartResponse = await api.get(`/store/carts/${cartFactory.id}`)
const cart = getCartResponse.data.cart
await api.post(`/store/carts/${cart.id}/payment-sessions`)
const createdOrder = await api.post(`/store/carts/${cart.id}/complete-cart`)
const createdOrder = await api.post(
`/store/carts/${cart.id}/complete-cart`
)
expect(createdOrder.data.data).toEqual(
expect.objectContaining({
@@ -232,12 +248,12 @@ describe("[MEDUSA_FF_TAX_INCLUSIVE_PRICING] Gift Card - Tax calculations", () =>
refundable: 50000,
tax_lines: expect.arrayContaining([
expect.objectContaining({
rate: 19
})
rate: 19,
}),
]),
})
}),
]),
}),
})
)
})
})
@@ -67,7 +67,9 @@ describe("/store/carts", () => {
})
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfile.default,
},
})
await manager.insert(Product, {
id: "test-product",
@@ -313,7 +315,7 @@ describe("/store/carts", () => {
MedusaError.Codes.INSUFFICIENT_INVENTORY
)
let payments = await manager.find(Payment, { cart_id: cartId })
let payments = await manager.find(Payment, { where: { cart_id: cartId } })
expect(payments).toHaveLength(1)
expect(payments).toContainEqual(
expect.objectContaining({
@@ -338,7 +340,7 @@ describe("/store/carts", () => {
expect(responseSuccess.status).toEqual(200)
expect(responseSuccess.data.type).toEqual("order")
payments = await manager.find(Payment, { cart_id: cartId })
payments = await manager.find(Payment, { where: { cart_id: cartId } })
expect(payments).toHaveLength(2)
expect(payments).toEqual(
expect.arrayContaining([
@@ -391,7 +393,9 @@ describe("/store/carts", () => {
expect(responseSuccess.status).toEqual(200)
expect(responseSuccess.data.type).toEqual("order")
const payments = await manager.find(Payment, { cart_id: cartId })
const payments = await manager.find(Payment, {
where: { cart_id: cartId },
})
expect(payments).toHaveLength(1)
expect(payments).toContainEqual(
expect.objectContaining({
@@ -48,7 +48,9 @@ describe("/store/carts", () => {
)
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfile.default,
},
})
await manager.insert(Region, {
@@ -1,5 +1,10 @@
const path = require("path")
const { Region, ShippingProfile, ShippingOption } = require("@medusajs/medusa")
const {
Region,
ShippingProfile,
ShippingOption,
ShippingProfileType,
} = require("@medusajs/medusa")
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
@@ -60,7 +65,9 @@ describe("/store/shipping-options", () => {
})
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfileType.DEFAULT,
},
})
await manager.insert(ShippingOption, {
@@ -1,5 +1,9 @@
const path = require("path")
const { ShippingProfile, ShippingOption } = require("@medusajs/medusa")
const {
ShippingProfile,
ShippingOption,
ShippingProfileType,
} = require("@medusajs/medusa")
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
@@ -38,7 +42,9 @@ describe("/store/carts", () => {
)
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfileType.DEFAULT,
},
})
await manager.insert(ShippingOption, {
id: "return-option",
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { Address } from "@medusajs/medusa"
@@ -11,7 +11,7 @@ export type AddressFactoryData = {
}
export const simpleAddressFactory = async (
connection: Connection,
dataSource: DataSource,
data: AddressFactoryData = {},
seed?: number
): Promise<Address> => {
@@ -19,7 +19,7 @@ export const simpleAddressFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const address = manager.create(Address, {
id: `simple-id-${Math.random() * 1000}`,
@@ -1,5 +1,5 @@
import { AnalyticsConfig } from "@medusajs/medusa"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
export type AnalyticsConfigData = {
id?: string
@@ -9,10 +9,10 @@ export type AnalyticsConfigData = {
}
export const simpleAnalyticsConfigFactory = async (
connection: Connection,
dataSource: DataSource,
data: AnalyticsConfigData = {}
): Promise<AnalyticsConfig> => {
const manager = connection.manager
const manager = dataSource.manager
const job = manager.create<AnalyticsConfig>(AnalyticsConfig, {
id: data.id ?? "test-analytics-config",
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import { BatchJob, BatchJobStatus } from "@medusajs/medusa"
export type BatchJobFactoryData = {
@@ -12,10 +12,10 @@ export type BatchJobFactoryData = {
}
export const simpleBatchJobFactory = async (
connection: Connection,
dataSource: DataSource,
data: BatchJobFactoryData = {}
): Promise<BatchJob> => {
const manager = connection.manager
const manager = dataSource.manager
const job = manager.create<BatchJob>(BatchJob, {
id: data.id,
@@ -1,6 +1,6 @@
import { Cart } from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import {
AddressFactoryData,
simpleAddressFactory,
@@ -32,7 +32,7 @@ export type CartFactoryData = {
}
export const simpleCartFactory = async (
connection: Connection,
dataSource: DataSource,
data: CartFactoryData = {},
seed?: number
): Promise<Cart> => {
@@ -40,37 +40,37 @@ export const simpleCartFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
let regionId: string
if (typeof data.region === "string") {
regionId = data.region
} else {
const region = await simpleRegionFactory(connection, data.region)
const region = await simpleRegionFactory(dataSource, data.region)
regionId = region.id
}
let customerId: string
let customerId!: string
if (typeof data.customer === "string") {
customerId = data.customer
} else {
if (data?.customer?.email) {
const customer = await simpleCustomerFactory(connection, data.customer)
const customer = await simpleCustomerFactory(dataSource, data.customer)
customerId = customer.id
} else if (data.email) {
const customer = await simpleCustomerFactory(connection, {
const customer = await simpleCustomerFactory(dataSource, {
email: data.email,
})
customerId = customer.id
}
}
const address = await simpleAddressFactory(connection, data.shipping_address)
const address = await simpleAddressFactory(dataSource, data.shipping_address)
let sales_channel
if (typeof data.sales_channel !== "undefined") {
sales_channel = await simpleSalesChannelFactory(
connection,
dataSource,
data.sales_channel
)
}
@@ -90,12 +90,12 @@ export const simpleCartFactory = async (
const shippingMethods = data.shipping_methods || []
for (const sm of shippingMethods) {
await simpleShippingMethodFactory(connection, { ...sm, cart_id: id })
await simpleShippingMethodFactory(dataSource, { ...sm, cart_id: id })
}
const items = data.line_items || []
for (const item of items) {
await simpleLineItemFactory(connection, { ...item, cart_id: id })
await simpleLineItemFactory(dataSource, { ...item, cart_id: id })
}
return cart
@@ -1,8 +1,6 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import {
CustomShippingOption,
} from "@medusajs/medusa"
import { CustomShippingOption } from "@medusajs/medusa"
export type CustomShippingOptionFactoryData = {
id?: string
@@ -13,7 +11,7 @@ export type CustomShippingOptionFactoryData = {
}
export const simpleCustomShippingOptionFactory = async (
connection: Connection,
dataSource: DataSource,
data: CustomShippingOptionFactoryData,
seed?: number
): Promise<CustomShippingOption> => {
@@ -21,14 +19,14 @@ export const simpleCustomShippingOptionFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const customShippingOptionData = {
id: data.id ?? `custon-simple-so-${Math.random() * 1000}`,
price: typeof data.price !== "undefined" ? data.price : 500,
cart_id: data.cart_id,
shipping_option_id: data.shipping_option_id,
metadata: data.metadata ?? {}
metadata: data.metadata ?? {},
}
const created = manager.create(CustomShippingOption, customShippingOptionData)
@@ -1,10 +1,7 @@
import faker from "faker"
import { Customer } from "@medusajs/medusa"
import { Connection } from "typeorm"
import {
CustomerGroupFactoryData,
simpleCustomerGroupFactory,
} from "./simple-customer-group-factory"
import { DataSource } from "typeorm"
import { Customer, CustomerGroup } from "@medusajs/medusa"
import { CustomerGroupFactoryData, simpleCustomerGroupFactory, } from "./simple-customer-group-factory"
export type CustomerFactoryData = {
id?: string
@@ -18,7 +15,7 @@ export type CustomerFactoryData = {
}
export const simpleCustomerFactory = async (
connection: Connection,
dataSource: DataSource,
data: CustomerFactoryData = {},
seed?: number
): Promise<Customer> => {
@@ -26,7 +23,7 @@ export const simpleCustomerFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const customerId = data.id || `simple-customer-${Math.random() * 1000}`
const c = manager.create(Customer, {
@@ -49,9 +46,9 @@ export const simpleCustomerFactory = async (
const customer = await manager.save(c)
if (data.groups) {
const groups = []
const groups: CustomerGroup[] = []
for (const g of data.groups) {
const created = await simpleCustomerGroupFactory(connection, g)
const created = await simpleCustomerGroupFactory(dataSource, g)
groups.push(created)
}
@@ -1,6 +1,6 @@
import { CustomerGroup } from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
export type CustomerGroupFactoryData = {
id?: string
@@ -8,7 +8,7 @@ export type CustomerGroupFactoryData = {
}
export const simpleCustomerGroupFactory = async (
connection: Connection,
dataSource: DataSource,
data: CustomerGroupFactoryData = {},
seed?: number
): Promise<CustomerGroup> => {
@@ -16,7 +16,7 @@ export const simpleCustomerGroupFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const customerGroupId =
data.id || `simple-customer-group-${Math.random() * 1000}`
@@ -10,7 +10,7 @@ import { DiscountConditionProductTag } from "@medusajs/medusa/dist/models/discou
import { DiscountConditionProductType } from "@medusajs/medusa/dist/models/discount-condition-product-type"
import { DiscountConditionJoinTableForeignKey } from "@medusajs/medusa/dist/repositories/discount-condition"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
export type DiscountConditionFactoryData = {
id?: string
@@ -66,7 +66,7 @@ const getJoinTableResourceIdentifiers = (type: string) => {
}
export const simpleDiscountConditionFactory = async (
connection: Connection,
dataSource: DataSource,
data: DiscountConditionFactoryData,
seed?: number
): Promise<void> => {
@@ -74,7 +74,7 @@ export const simpleDiscountConditionFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
let resources = []
@@ -2,13 +2,13 @@ import {
AllocationType,
Discount,
DiscountRule,
DiscountRuleType
DiscountRuleType,
} from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import {
DiscountConditionFactoryData,
simpleDiscountConditionFactory
simpleDiscountConditionFactory,
} from "./simple-discount-condition-factory"
export type DiscountRuleFactoryData = {
@@ -29,7 +29,7 @@ export type DiscountFactoryData = {
}
export const simpleDiscountFactory = async (
connection: Connection,
dataSource: DataSource,
data: DiscountFactoryData = {},
seed?: number
): Promise<Discount> => {
@@ -37,7 +37,7 @@ export const simpleDiscountFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const ruleData = data.rule ?? ({} as DiscountRuleFactoryData)
const ruleToSave = manager.create(DiscountRule, {
@@ -51,7 +51,7 @@ export const simpleDiscountFactory = async (
if (data?.rule?.conditions) {
for (const condition of data.rule.conditions) {
await simpleDiscountConditionFactory(
connection,
dataSource,
{ ...condition, rule_id: dRule.id },
1
)
@@ -1,6 +1,6 @@
import { GiftCard } from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
export type GiftCardFactoryData = {
id?: string
@@ -12,7 +12,7 @@ export type GiftCardFactoryData = {
}
export const simpleGiftCardFactory = async (
connection: Connection,
dataSource: DataSource,
data: GiftCardFactoryData,
seed?: number
): Promise<GiftCard> => {
@@ -20,7 +20,7 @@ export const simpleGiftCardFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const toSave = manager.create(GiftCard, {
id: data.id,
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { LineItem, LineItemAdjustment, LineItemTaxLine } from "@medusajs/medusa"
@@ -36,7 +36,7 @@ export type LineItemFactoryData = {
}
export const simpleLineItemFactory = async (
connection: Connection,
dataSource: DataSource,
data: LineItemFactoryData,
seed?: number
): Promise<LineItem> => {
@@ -52,7 +52,7 @@ export const simpleLineItemFactory = async (
Math
}
const manager = connection.manager
const manager = dataSource.manager
const id = data.id || `simple-line-${Math.random() * 1000}`
const toSave = manager.create(LineItem, {
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import { OrderFactoryData, simpleOrderFactory } from "./simple-order-factory"
import { OrderEdit } from "@medusajs/medusa"
@@ -22,13 +22,13 @@ export type OrderEditFactoryData = {
}
export const simpleOrderEditFactory = async (
connection: Connection,
dataSource: DataSource,
data: OrderEditFactoryData = {}
): Promise<OrderEdit> => {
const manager = connection.manager
const manager = dataSource.manager
if (!data.order_id) {
const order = await simpleOrderFactory(connection, data.order)
const order = await simpleOrderFactory(dataSource, data.order)
data.order_id = order.id
}
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import {
Discount,
@@ -51,7 +51,7 @@ export type OrderFactoryData = {
}
export const simpleOrderFactory = async (
connection: Connection,
dataSource: DataSource,
data: OrderFactoryData = {} as OrderFactoryData,
seed?: number
): Promise<Order> => {
@@ -59,7 +59,7 @@ export const simpleOrderFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
let currencyCode: string
let regionId: string
@@ -70,16 +70,16 @@ export const simpleOrderFactory = async (
regionId = data.region
taxRate = data.tax_rate as number
} else {
const region = await simpleRegionFactory(connection, data.region)
const region = await simpleRegionFactory(dataSource, data.region)
taxRate =
(typeof data.tax_rate !== "undefined" ? data.tax_rate : region.tax_rate) as number
currencyCode = region.currency_code
regionId = region.id
}
const address = await simpleAddressFactory(connection, data.shipping_address)
const address = await simpleAddressFactory(dataSource, data.shipping_address)
const customer = await simpleCustomerFactory(connection, {
const customer = await simpleCustomerFactory(dataSource, {
...data.customer,
email: data.email ?? undefined,
})
@@ -87,14 +87,14 @@ export const simpleOrderFactory = async (
let discounts: Discount[] = []
if (typeof data.discounts !== "undefined") {
discounts = await Promise.all(
data.discounts.map((d) => simpleDiscountFactory(connection, d, seed))
data.discounts.map((d) => simpleDiscountFactory(dataSource, d, seed))
)
}
let sales_channel
if (typeof data.sales_channel !== "undefined") {
sales_channel = await simpleSalesChannelFactory(
connection,
dataSource,
data.sales_channel
)
}
@@ -120,7 +120,7 @@ export const simpleOrderFactory = async (
const shippingMethods = data.shipping_methods || []
for (const sm of shippingMethods) {
await simpleShippingMethodFactory(connection, { ...sm, order_id: order.id })
await simpleShippingMethodFactory(dataSource, { ...sm, order_id: order.id })
}
const items =
@@ -136,7 +136,7 @@ export const simpleOrderFactory = async (
}) || []
for (const item of items) {
await simpleLineItemFactory(connection, { ...item, order_id: id } as unknown as LineItemFactoryData)
await simpleLineItemFactory(dataSource, { ...item, order_id: id } as unknown as LineItemFactoryData)
}
return order
@@ -1,9 +1,5 @@
import {
OrderEdit,
OrderEditItemChangeType,
OrderItemChange,
} from "@medusajs/medusa"
import { Connection } from "typeorm"
import { OrderEditItemChangeType, OrderItemChange } from "@medusajs/medusa"
import { DataSource } from "typeorm"
type OrderItemChangeData = {
id: string
@@ -14,10 +10,10 @@ type OrderItemChangeData = {
}
export const simpleOrderItemChangeFactory = async (
connection: Connection,
dataSource: DataSource,
data: OrderItemChangeData
) => {
const manager = connection.manager
const manager = dataSource.manager
const change = manager.create<OrderItemChange>(OrderItemChange, {
id: data.id,
type: data.type,
@@ -1,14 +1,14 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import { simpleRegionFactory } from "./simple-region-factory"
import { simplePaymentFactory } from "./simple-payment-factory"
import { Payment, PaymentCollection } from "@medusajs/medusa"
export const simplePaymentCollectionFactory = async (
connection: Connection,
dataSource: DataSource,
data: Partial<PaymentCollection> = {}
): Promise<PaymentCollection> => {
const manager = connection.manager
const manager = dataSource.manager
const defaultData = {
currency_code: data.currency_code ?? "usd",
@@ -19,7 +19,7 @@ export const simplePaymentCollectionFactory = async (
}
if (!data.region && !data.region_id) {
data.region = await simpleRegionFactory(connection, {
data.region = await simpleRegionFactory(dataSource, {
id: data.region_id || "test-region",
currency_code: defaultData.currency_code,
})
@@ -32,7 +32,7 @@ export const simplePaymentCollectionFactory = async (
payment.currency_code = payment.currency_code ?? defaultData.currency_code
const savedPayment = await simplePaymentFactory(
connection,
dataSource,
payment as any
)
payments.push(savedPayment)
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import { Payment } from "@medusajs/medusa"
export type PaymentFactoryData = {
@@ -12,11 +12,11 @@ export type PaymentFactoryData = {
}
export const simplePaymentFactory = async (
connection: Connection,
dataSource: DataSource,
data: PaymentFactoryData,
_?: number
): Promise<Payment> => {
const manager = connection.manager
const manager = dataSource.manager
let captured_at = data.captured
if (typeof captured_at === "boolean") {
@@ -6,7 +6,7 @@ import {
PriceListType,
} from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import { simpleCustomerGroupFactory } from "./simple-customer-group-factory"
type ProductListPrice = {
@@ -30,7 +30,7 @@ export type PriceListFactoryData = {
}
export const simplePriceListFactory = async (
connection: Connection,
dataSource: DataSource,
data: PriceListFactoryData = {},
seed?: number
): Promise<PriceList> => {
@@ -38,7 +38,7 @@ export const simplePriceListFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const listId = data.id || `simple-price-list-${Math.random() * 1000}`
@@ -46,7 +46,7 @@ export const simplePriceListFactory = async (
if (typeof data.customer_groups !== "undefined") {
customerGroups = await Promise.all(
data.customer_groups.map((group) =>
simpleCustomerGroupFactory(connection, { id: group })
simpleCustomerGroupFactory(dataSource, { id: group })
)
)
}
@@ -1,12 +1,12 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import { ProductCategory } from "@medusajs/medusa"
export const simpleProductCategoryFactory = async (
connection: Connection,
dataSource: DataSource,
data: Partial<ProductCategory> = {}
): Promise<ProductCategory> => {
const manager = connection.manager
const category = manager.create(ProductCategory, data)
const manager = dataSource.manager
const productCategory = manager.create(ProductCategory, data)
return await manager.save(category)
return await manager.save(productCategory)
}
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { ProductCollection } from "@medusajs/medusa"
@@ -11,7 +11,7 @@ export const simpleProductCollectionFactory = async <
TData extends Data | Data[] = Data | Data[],
TResult = TData extends Array<Data> ? ProductCollection[] : ProductCollection
>(
connection: Connection,
dataSource: DataSource,
data?: TData,
seed?: number
): Promise<TResult> => {
@@ -19,7 +19,7 @@ export const simpleProductCollectionFactory = async <
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
data = data || [{
title: faker.datatype.string(10),
@@ -8,7 +8,7 @@ import {
Store,
} from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import {
ProductVariantFactoryData,
simpleProductVariantFactory,
@@ -32,22 +32,26 @@ export type ProductFactoryData = {
}
export const simpleProductFactory = async (
connection: Connection,
dataSource: DataSource,
data: ProductFactoryData = {},
seed?: number
): Promise<Product | undefined> => {
): Promise<Product | undefined | null> => {
if (typeof seed !== "undefined") {
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: ShippingProfileType.DEFAULT,
where: {
type: ShippingProfileType.DEFAULT,
}
})
const gcProfile = await manager.findOne(ShippingProfile, {
type: ShippingProfileType.GIFT_CARD,
where: {
type: ShippingProfileType.GIFT_CARD,
}
})
let sales_channels
@@ -55,18 +59,20 @@ export const simpleProductFactory = async (
sales_channels = await Promise.all(
data.sales_channels.map(
async (salesChannel) =>
await simpleSalesChannelFactory(connection, salesChannel)
await simpleSalesChannelFactory(dataSource, salesChannel)
)
)
} else {
const store = await manager.findOne(Store, {
relations: ["default_sales_channel"],
const stores = await manager.find(Store, {
relations: { default_sales_channel: true },
})
const store = stores[0]
if (store?.default_sales_channel) {
sales_channels = [store.default_sales_channel]
} else {
const salesChannel = await simpleSalesChannelFactory(connection, {
const salesChannel = await simpleSalesChannelFactory(dataSource, {
id: `default-${Math.random() * 1000}`,
is_default: true,
})
@@ -144,12 +150,16 @@ export const simpleProductFactory = async (
{ option_id: optionId, value: faker.commerce.productAdjective() },
]
}
await simpleProductVariantFactory(connection, factoryData)
await simpleProductVariantFactory(dataSource, factoryData)
}
return await manager.findOne(
Product,
{ id: prodId },
{ relations: ["tags", "variants", "variants.prices"] }
{
where: {
id: prodId
},
relations: { tags: true, variants: { prices: true }}
}
)
}
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { ProductTaxRate, TaxRate } from "@medusajs/medusa"
@@ -15,7 +15,7 @@ export type ProductTaxRateFactoryData = {
}
export const simpleProductTaxRateFactory = async (
connection: Connection,
dataSource: DataSource,
data: ProductTaxRateFactoryData,
seed?: number
): Promise<ProductTaxRate> => {
@@ -23,7 +23,7 @@ export const simpleProductTaxRateFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
let rateId: string
if (typeof data.rate === "string") {
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { ProductTypeTaxRate, TaxRate } from "@medusajs/medusa"
@@ -15,7 +15,7 @@ export type ProductTypeTaxRateFactoryData = {
}
export const simpleProductTypeTaxRateFactory = async (
connection: Connection,
dataSource: DataSource,
data: ProductTypeTaxRateFactoryData,
seed?: number
): Promise<ProductTypeTaxRate> => {
@@ -23,7 +23,7 @@ export const simpleProductTypeTaxRateFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
let rateId: string
if (typeof data.rate === "string") {
@@ -1,9 +1,9 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import {
MoneyAmount,
ProductOptionValue,
ProductVariant,
MoneyAmount,
} from "@medusajs/medusa"
export type ProductVariantFactoryData = {
@@ -18,7 +18,7 @@ export type ProductVariantFactoryData = {
}
export const simpleProductVariantFactory = async (
connection: Connection,
dataSource: DataSource,
data: ProductVariantFactoryData,
seed?: number
): Promise<ProductVariant> => {
@@ -26,7 +26,7 @@ export const simpleProductVariantFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const id = data.id || `simple-variant-${Math.random() * 1000}`
const toSave = manager.create(ProductVariant, {
@@ -1,5 +1,5 @@
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import { PublishableApiKey } from "@medusajs/medusa"
@@ -12,10 +12,10 @@ export type PublishableApiKeyData = {
}
export const simplePublishableApiKeyFactory = async (
connection: Connection,
dataSource: DataSource,
data: PublishableApiKeyData = {}
): Promise<PublishableApiKey> => {
const manager = connection.manager
const manager = dataSource.manager
const pubKey = manager.create(PublishableApiKey, {
...data,
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { Region } from "@medusajs/medusa"
@@ -15,7 +15,7 @@ export type RegionFactoryData = {
}
export const simpleRegionFactory = async (
connection: Connection,
dataSource: DataSource,
data: RegionFactoryData = {},
seed?: number
): Promise<Region> => {
@@ -23,7 +23,7 @@ export const simpleRegionFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const regionId = data.id || `simple-region-${Math.random() * 1000}`
const r = manager.create(Region, {
@@ -1,18 +1,18 @@
import { Product, SalesChannel } from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
export type SalesChannelFactoryData = {
name?: string
description?: string
is_disabled?: boolean
id?: string
products?: Product[],
products?: Product[]
is_default?: boolean
}
export const simpleSalesChannelFactory = async (
connection: Connection,
dataSource: DataSource,
data: SalesChannelFactoryData = {},
seed?: number
): Promise<SalesChannel> => {
@@ -20,7 +20,7 @@ export const simpleSalesChannelFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
let salesChannel = manager.create(SalesChannel, {
id: data.id ?? `simple-id-${Math.random() * 1000}`,
@@ -1,6 +1,6 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { ShippingMethodTaxLine, ShippingMethod } from "@medusajs/medusa"
import { ShippingMethod, ShippingMethodTaxLine } from "@medusajs/medusa"
import {
ShippingOptionFactoryData,
@@ -19,7 +19,7 @@ export type ShippingMethodFactoryData = {
}
export const simpleShippingMethodFactory = async (
connection: Connection,
dataSource: DataSource,
data: ShippingMethodFactoryData,
seed?: number
): Promise<ShippingMethod> => {
@@ -27,14 +27,14 @@ export const simpleShippingMethodFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
let shippingOptionId: string
if (typeof data.shipping_option === "string") {
shippingOptionId = data.shipping_option
} else {
const option = await simpleShippingOptionFactory(
connection,
dataSource,
data.shipping_option
)
shippingOptionId = option.id
@@ -6,7 +6,7 @@ import {
ShippingProfileType,
} from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import { simpleRegionFactory } from "./simple-region-factory"
export type ShippingOptionFactoryData = {
@@ -28,7 +28,7 @@ type ShippingOptionRequirementData = {
}
export const simpleShippingOptionFactory = async (
connection: Connection,
dataSource: DataSource,
data: ShippingOptionFactoryData = {},
seed?: number
): Promise<ShippingOption> => {
@@ -36,19 +36,23 @@ export const simpleShippingOptionFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: ShippingProfileType.DEFAULT,
where: {
type: ShippingProfileType.DEFAULT,
}
})
const gcProfile = await manager.findOne(ShippingProfile, {
type: ShippingProfileType.GIFT_CARD,
where: {
type: ShippingProfileType.GIFT_CARD,
}
})
let region_id = data.region_id
if (!region_id) {
const { id } = await simpleRegionFactory(connection)
const { id } = await simpleRegionFactory(dataSource)
region_id = id
}
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { ShippingTaxRate, TaxRate } from "@medusajs/medusa"
@@ -15,7 +15,7 @@ export type ShippingTaxRateFactoryData = {
}
export const simpleShippingTaxRateFactory = async (
connection: Connection,
dataSource: DataSource,
data: ShippingTaxRateFactoryData,
seed?: number
): Promise<ShippingTaxRate> => {
@@ -23,7 +23,7 @@ export const simpleShippingTaxRateFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
let rateId: string
if (typeof data.rate === "string") {
@@ -1,4 +1,4 @@
import { Connection } from "typeorm"
import { DataSource } from "typeorm"
import faker from "faker"
import { TaxRate } from "@medusajs/medusa"
@@ -10,7 +10,7 @@ export type TaxRateFactoryData = {
}
export const simpleTaxRateFactory = async (
connection: Connection,
dataSource: DataSource,
data: TaxRateFactoryData,
seed?: number
): Promise<TaxRate> => {
@@ -18,7 +18,7 @@ export const simpleTaxRateFactory = async (
faker.seed(seed)
}
const manager = connection.manager
const manager = dataSource.manager
const toSave = manager.create(TaxRate, {
region_id: data.region_id,
@@ -1,8 +1,8 @@
const Scrypt = require("scrypt-kdf")
const { User } = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const buf = await Scrypt.kdf("secret_password", { logN: 1, r: 1, p: 1 })
const password_hash = buf.toString("base64")
@@ -11,8 +11,8 @@ const {
ProductOption,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const yesterday = ((today) => new Date(today.setDate(today.getDate() - 1)))(
new Date()
@@ -23,7 +23,7 @@ module.exports = async (connection, data = {}) => {
)
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: { type: ShippingProfile.default },
})
const collection = manager.create(ProductCollection, {
@@ -1,7 +1,7 @@
const { Region } = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
await manager.insert(Region, {
id: "region-product-import-0",
+5 -4
View File
@@ -16,9 +16,10 @@ const {
PaymentSession,
CustomerGroup,
PriceList,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
module.exports = async (dataSource, data = {}) => {
const yesterday = ((today) => new Date(today.setDate(today.getDate() - 1)))(
new Date()
)
@@ -31,14 +32,14 @@ module.exports = async (connection, data = {}) => {
const tenDaysFromToday = ((today) =>
new Date(today.setDate(today.getDate() + 10)))(new Date())
const manager = connection.manager
const manager = dataSource.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: { type: ShippingProfileType.DEFAULT },
})
const gcProfile = await manager.findOne(ShippingProfile, {
type: "gift_card",
where: { type: ShippingProfileType.GIFT_CARD },
})
await manager.insert(Address, {
@@ -6,8 +6,8 @@ const {
Return,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
let orderWithClaim = manager.create(Order, {
id: "order-with-claim",
@@ -1,7 +1,7 @@
const { Customer, Address, CustomerGroup } = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const testAddr = await manager.create(Address, {
id: "test-address",
@@ -4,8 +4,8 @@ const {
Discount,
DiscountRule,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
await manager.insert(Region, {
id: "test-region",
@@ -14,17 +14,18 @@ const {
Discount,
DiscountRule,
Payment,
ShippingProfileType,
} = require("@medusajs/medusa")
const { simpleSalesChannelFactory } = require("../factories")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: { type: ShippingProfileType.DEFAULT },
})
const salesChannel = await simpleSalesChannelFactory(connection, {
const salesChannel = await simpleSalesChannelFactory(dataSource, {
id: "sales-channel",
is_default: true,
})
@@ -13,17 +13,18 @@ const {
ShippingOption,
ShippingProfile,
Swap,
ShippingProfileType,
} = require("@medusajs/medusa")
const { simpleSalesChannelFactory } = require("../factories")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: { type: ShippingProfileType.DEFAULT },
})
const salesChannel = await simpleSalesChannelFactory(connection, {
const salesChannel = await simpleSalesChannelFactory(dataSource, {
id: "test-channel",
is_default: true,
})
@@ -1,7 +1,7 @@
const { Region, PriceList, MoneyAmount } = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const priceListNoCustomerGroups = await manager.create(PriceList, {
id: "pl_no_customer_groups",
@@ -9,9 +9,10 @@ const {
Region,
Cart,
PriceList,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
module.exports = async (dataSource, data = {}) => {
const yesterday = ((today) => new Date(today.setDate(today.getDate() - 1)))(
new Date()
)
@@ -24,10 +25,10 @@ module.exports = async (connection, data = {}) => {
const tenDaysFromToday = ((today) =>
new Date(today.setDate(today.getDate() + 10)))(new Date())
const manager = connection.manager
const manager = dataSource.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: { type: ShippingProfileType.DEFAULT },
})
await manager.insert(Region, {
@@ -8,14 +8,16 @@ const {
ShippingProfile,
ProductVariant,
Image,
Store,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfileType.DEFAULT,
},
})
const coll = await manager.create(ProductCollection, {
@@ -3,10 +3,11 @@ const {
ShippingProfile,
ShippingOption,
ShippingOptionRequirement,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
await manager.insert(Region, {
id: "region",
@@ -16,7 +17,7 @@ module.exports = async (connection, data = {}) => {
})
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: { type: ShippingProfileType.DEFAULT },
})
await manager.insert(ShippingOption, {
@@ -10,10 +10,11 @@ const {
Image,
Cart,
PriceList,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const yesterday = ((today) => new Date(today.setDate(today.getDate() - 1)))(
new Date()
@@ -48,7 +49,7 @@ module.exports = async (connection, data = {}) => {
await manager.save(priceList1)
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: { type: ShippingProfileType.DEFAULT },
})
const coll = manager.create(ProductCollection, {
+3 -3
View File
@@ -16,12 +16,12 @@ const { Region } = require("@medusajs/medusa/dist/models/region")
let regionId
let region
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
regionId = "test-region"
region = await manager.findOne(Region, { id: regionId })
region = await manager.findOne(Region, { where: { id: regionId } })
let orderWithSwap = manager.create(Order, {
id: "order-with-swap",
+2 -2
View File
@@ -11,8 +11,8 @@ const expires_at = new Date()
expires_at.setDate(expires_at.getDate() + 8)
module.exports = async (connection, data = {}) => {
const manager = connection.manager
module.exports = async (dataSource, data = {}) => {
const manager = dataSource.manager
const memberUser = await manager.create(User, {
id: "member-user",
+1 -1
View File
@@ -12,7 +12,7 @@
"@medusajs/medusa": "*",
"faker": "^5.5.3",
"medusa-interfaces": "*",
"typeorm": "^0.2.31"
"typeorm": "^0.3.11"
},
"devDependencies": {
"@babel/cli": "^7.12.10",
+19 -17
View File
@@ -2,7 +2,7 @@ const path = require("path")
const { getConfigFile } = require("medusa-core-utils")
const { dropDatabase } = require("pg-god")
const { createConnection } = require("typeorm")
const { DataSource } = require("typeorm")
const dbFactory = require("./use-template-db")
const DB_HOST = process.env.DB_HOST
@@ -27,13 +27,13 @@ const keepTables = [
"currency",
]
let connectionType = "postgresql"
let dataSourceType = "postgresql"
const DbTestUtil = {
db_: null,
setDb: function (connection) {
this.db_ = connection
setDb: function (dataSource) {
this.db_ = dataSource
},
clear: async function () {
@@ -47,7 +47,7 @@ const DbTestUtil = {
const manager = this.db_.manager
if (connectionType === "sqlite") {
if (dataSourceType === "sqlite") {
await manager.query(`PRAGMA foreign_keys = OFF`)
} else {
await manager.query(`SET session_replication_role = 'replica';`)
@@ -64,7 +64,7 @@ const DbTestUtil = {
await manager.query(`DELETE
FROM "${entity.tableName}";`)
}
if (connectionType === "sqlite") {
if (dataSourceType === "sqlite") {
await manager.query(`PRAGMA foreign_keys = ON`)
} else {
await manager.query(`SET session_replication_role = 'origin';`)
@@ -72,7 +72,7 @@ const DbTestUtil = {
},
shutdown: async function () {
await this.db_.close()
await this.db_.destroy()
return await dropDatabase({ DB_NAME }, pgGodCredentials)
},
}
@@ -88,14 +88,12 @@ module.exports = {
require("@medusajs/medusa/dist/loaders/feature-flags").default
const featureFlagsRouter = featureFlagsLoader({ featureFlags })
const modelsLoader = require("@medusajs/medusa/dist/loaders/models").default
const entities = modelsLoader({}, { register: false })
if (projectConfig.database_type === "sqlite") {
connectionType = "sqlite"
const dbConnection = await createConnection({
dataSourceType = "sqlite"
const dataSource = new DataSource({
type: "sqlite",
database: projectConfig.database_database,
synchronize: true,
@@ -103,8 +101,10 @@ module.exports = {
extra: database_extra ?? {},
})
instance.setDb(dbConnection)
return dbConnection
const dbDataSource = await dataSource.initialize()
instance.setDb(dbDataSource)
return dbDataSource
} else {
await dbFactory.createFromTemplate(DB_NAME)
@@ -138,7 +138,7 @@ module.exports = {
(e) => typeof e.isFeatureEnabled === "undefined" || e.isFeatureEnabled()
)
const dbConnection = await createConnection({
const dbDataSource = new DataSource({
type: "postgres",
url: DB_URL,
entities: enabledEntities.concat(moduleModels),
@@ -147,10 +147,12 @@ module.exports = {
name: "integration-tests",
})
await dbConnection.runMigrations()
await dbDataSource.initialize()
instance.setDb(dbConnection)
return dbConnection
await dbDataSource.runMigrations()
instance.setDb(dbDataSource)
return dbDataSource
}
},
useDb: function () {
+28 -27
View File
@@ -4,13 +4,15 @@ require("dotenv").config({ path: path.join(__dirname, "../.env.test") })
const { getConfigFile } = require("medusa-core-utils")
const { createDatabase, dropDatabase } = require("pg-god")
const { createConnection, getConnection } = require("typeorm")
const { DataSource } = require("typeorm")
const DB_HOST = process.env.DB_HOST
const DB_USERNAME = process.env.DB_USERNAME
const DB_PASSWORD = process.env.DB_PASSWORD
const DB_URL = `postgres://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}`
let masterDataSource
const pgGodCredentials = {
user: DB_USERNAME,
password: DB_PASSWORD,
@@ -19,16 +21,14 @@ const pgGodCredentials = {
class DatabaseFactory {
constructor() {
this.connection_ = null
this.masterConnectionName = "master"
this.dataSource_ = null
this.masterDataSourceName = "master"
this.templateDbName = "medusa-integration-template"
}
async createTemplateDb_({ cwd }) {
const { configModule } = getConfigFile(cwd, `medusa-config`)
const connection = await this.getMasterConnection()
const dataSource = await this.getMasterDataSource()
const migrationDir = path.resolve(
path.join(
__dirname,
@@ -68,51 +68,52 @@ class DatabaseFactory {
pgGodCredentials
)
const templateDbConnection = await createConnection({
const templateDbDataSource = new DataSource({
type: "postgres",
name: "templateConnection",
name: "templateDataSource",
url: `${DB_URL}/${this.templateDbName}`,
migrations: enabledMigrations.concat(moduleMigrations),
})
await templateDbConnection.runMigrations()
await templateDbConnection.close()
await templateDbDataSource.initialize()
return connection
await templateDbDataSource.runMigrations()
await templateDbDataSource.destroy()
return dataSource
}
async getMasterConnection() {
try {
return getConnection(this.masterConnectionName)
} catch (err) {
return await this.createMasterConnection()
}
async getMasterDataSource() {
masterDataSource = masterDataSource || (await this.createMasterDataSource())
return masterDataSource
}
async createMasterConnection() {
const connection = await createConnection({
async createMasterDataSource() {
const dataSource = new DataSource({
type: "postgres",
name: this.masterConnectionName,
name: this.masterDataSourceName,
url: `${DB_URL}`,
})
await dataSource.initialize()
return connection
return dataSource
}
async createFromTemplate(dbName) {
const connection = await this.getMasterConnection()
const dataSource = await this.getMasterDataSource()
await connection.query(`DROP DATABASE IF EXISTS "${dbName}";`)
await connection.query(
await dataSource.query(`DROP DATABASE IF EXISTS "${dbName}";`)
await dataSource.query(
`CREATE DATABASE "${dbName}" TEMPLATE "${this.templateDbName}";`
)
}
async destroy() {
const connection = await this.getMasterConnection()
const dataSource = await this.getMasterDataSource()
await connection.query(`DROP DATABASE IF EXISTS "${this.templateDbName}";`)
await connection.close()
await dataSource.query(`DROP DATABASE IF EXISTS "${this.templateDbName}";`)
await dataSource.destroy()
}
}
@@ -302,7 +302,8 @@ describe("Inventory Items endpoints", () => {
const response = await api.get(`/admin/inventory-items`, adminHeaders)
expect(response.data.inventory_items).toEqual([
expect(response.data.inventory_items).toHaveLength(1)
expect(response.data.inventory_items[0]).toEqual(
expect.objectContaining({
id: inventoryItemId,
sku: "MY_SKU",
@@ -359,8 +360,8 @@ describe("Inventory Items endpoints", () => {
available_quantity: 5,
}),
]),
}),
])
})
)
})
it("When deleting an inventory item it removes the product variants associated to it", async () => {
@@ -98,6 +98,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -254,6 +255,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -407,6 +409,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -525,6 +528,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -709,6 +713,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -875,6 +880,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -1130,6 +1136,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -1384,6 +1391,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -1598,6 +1606,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -1716,6 +1725,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -1900,6 +1910,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -2061,6 +2072,7 @@ Object {
"title": "Small Wooden Computer",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -2169,6 +2181,7 @@ Object {
"title": "Practical Granite Pizza",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -2291,6 +2304,7 @@ Object {
"title": "Small Wooden Computer",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -2407,6 +2421,7 @@ Object {
"title": "Small Wooden Computer",
"upc": null,
"updated_at": Any<Date>,
"variant_rank": 0,
"weight": null,
"width": null,
},
@@ -2414,7 +2429,6 @@ Object {
},
],
"allow_backorder": true,
"beforeInsert": [Function],
"canceled_at": null,
"cart_id": Any<String>,
"confirmed_at": Any<Date>,
@@ -6,7 +6,7 @@ const { setPort, useApi } = require("../../../helpers/use-api")
const adminSeeder = require("../../helpers/admin-seeder")
jest.setTimeout(30000)
jest.setTimeout(50000)
const {
simpleOrderFactory,
@@ -343,8 +343,6 @@ describe("medusa-plugin-sendgrid", () => {
expect(response.status).toEqual(200)
expect(response.status).toEqual(200)
const swap = response.data.order.swaps[0]
const returnOrder = swap.return_order
await api.post(
@@ -421,7 +419,6 @@ describe("medusa-plugin-sendgrid", () => {
price: 500,
})
const api = useApi()
const response = await api.post(
`/admin/orders/${order.id}/claims`,
{
@@ -557,11 +554,14 @@ describe("medusa-plugin-sendgrid", () => {
phone: "12353245",
},
})
await api.post(`/store/carts/${cartId}/shipping-methods`, {
option_id: shippingOut.id,
})
await api.post(`/store/carts/${cartId}/payment-sessions`)
await api.post(`/store/carts/${cartId}/complete`)
const { data: fulfillmentData } = await api.post(
`/admin/orders/${order.id}/swaps/${swapId}/fulfillments`,
{},
@@ -741,7 +741,6 @@ describe("medusa-plugin-sendgrid", () => {
const order = await createReturnableOrder(dbConnection)
const api = useApi()
const response = await api.post(
`/admin/orders/${order.id}/swaps`,
{
@@ -1,17 +1,8 @@
import { Connection } from "typeorm"
import faker from "faker"
import {
ShippingProfileType,
ShippingProfile,
Product,
ProductType,
ProductOption,
} from "@medusajs/medusa"
import { Product, ProductOption, ProductType, ShippingProfile, ShippingProfileType, } from "@medusajs/medusa"
import {
simpleProductVariantFactory,
ProductVariantFactoryData,
} from "./simple-product-variant-factory"
import { ProductVariantFactoryData, simpleProductVariantFactory, } from "./simple-product-variant-factory"
export type ProductFactoryData = {
id?: string
@@ -34,11 +25,11 @@ export const simpleProductFactory = async (
const manager = connection.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: ShippingProfileType.DEFAULT,
where: { type: ShippingProfileType.DEFAULT },
})
const gcProfile = await manager.findOne(ShippingProfile, {
type: ShippingProfileType.GIFT_CARD,
where: { type: ShippingProfileType.GIFT_CARD },
})
let typeId: string
@@ -1,11 +1,6 @@
import { Connection } from "typeorm"
import faker from "faker"
import {
ShippingOptionPriceType,
ShippingProfile,
ShippingOption,
ShippingProfileType,
} from "@medusajs/medusa"
import { ShippingOption, ShippingOptionPriceType, ShippingProfile, ShippingProfileType, } from "@medusajs/medusa"
export type ShippingOptionFactoryData = {
name?: string
@@ -26,11 +21,11 @@ export const simpleShippingOptionFactory = async (
const manager = connection.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: ShippingProfileType.DEFAULT,
where: { type: ShippingProfileType.DEFAULT },
})
const gcProfile = await manager.findOne(ShippingProfile, {
type: ShippingProfileType.GIFT_CARD,
where: { type: ShippingProfileType.GIFT_CARD },
})
const created = manager.create(ShippingOption, {
@@ -1,22 +1,27 @@
import { SalesChannel, Store } from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { DataSource, Not, IsNull } from "typeorm"
export type StoreFactoryData = {
swap_link_template?: string
}
export const simpleStoreFactory = async (
connection: Connection,
dataSource: DataSource,
data: StoreFactoryData = {},
seed?: number
): Promise<Store> => {
): Promise<Store | undefined> => {
if (typeof seed !== "undefined") {
faker.seed(seed)
}
const manager = connection.manager
const store = await manager.findOne(Store)
const manager = dataSource.manager
const stores = await manager.find(Store, { where: { id: Not(IsNull()) } })
const store = stores[0]
if (!store) {
return
}
store.swap_link_template = data.swap_link_template ?? "something/{cart_id}"
@@ -14,6 +14,7 @@ const {
LineItem,
Payment,
PaymentSession,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
@@ -34,11 +35,15 @@ module.exports = async (connection, data = {}) => {
const manager = connection.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfileType.DEFAULT,
},
})
const gcProfile = await manager.findOne(ShippingProfile, {
type: "gift_card",
where: {
type: ShippingProfileType.GIFT_CARD,
},
})
await manager.insert(Address, {
@@ -14,13 +14,16 @@ const {
Discount,
DiscountRule,
Payment,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfileType.DEFAULT,
},
})
await manager.insert(Product, {
@@ -13,13 +13,16 @@ const {
ShippingOption,
ShippingProfile,
Swap,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfileType.DEFAULT,
},
})
await manager.insert(Product, {
@@ -8,13 +8,16 @@ const {
ShippingProfile,
ProductVariant,
Image,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfileType.DEFAULT,
},
})
const coll = manager.create(ProductCollection, {
@@ -3,6 +3,7 @@ const {
ShippingProfile,
ShippingOption,
ShippingOptionRequirement,
ShippingProfileType,
} = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
@@ -16,7 +17,9 @@ module.exports = async (connection, data = {}) => {
})
const defaultProfile = await manager.findOne(ShippingProfile, {
type: "default",
where: {
type: ShippingProfileType.DEFAULT,
},
})
await manager.insert(ShippingOption, {
+1 -1
View File
@@ -14,7 +14,7 @@
"medusa-fulfillment-webshipper": "*",
"medusa-interfaces": "*",
"medusa-plugin-sendgrid": "*",
"typeorm": "^0.2.31"
"typeorm": "^0.3.11"
},
"devDependencies": {
"@babel/cli": "^7.12.10",
@@ -48,7 +48,7 @@ describe("Product Categories", () => {
is_active: false
})
productCategoryRepository = dbConnection.manager.getCustomRepository(ProductCategoryRepository)
productCategoryRepository = dbConnection.manager.withRepository(ProductCategoryRepository)
})
it("can fetch all root categories", async () => {
@@ -133,7 +133,7 @@ describe("Product Categories", () => {
}
)
productCategoryRepository = dbConnection.manager.getCustomRepository(ProductCategoryRepository)
productCategoryRepository = dbConnection.manager.withRepository(ProductCategoryRepository)
})
it("fetches all active categories", async () => {
@@ -200,7 +200,7 @@ describe("Product Categories", () => {
const [ categories, count ] = await productCategoryRepository.getFreeTextSearchResultsAndCount(
{
where: { id: a11.id },
relations: ['parent_category', 'category_children'],
relations: { parent_category: true, category_children: true },
},
)
+1 -1
View File
@@ -10,7 +10,7 @@
"dependencies": {
"@medusajs/medusa": "*",
"medusa-interfaces": "*",
"typeorm": "^0.2.31"
"typeorm": "^0.3.11"
},
"devDependencies": {
"@babel/cli": "^7.12.10",