feat(medusa): Migrate services to use TransactionBaseService (#2276)

This commit is contained in:
Adrien de Peretti
2022-09-29 15:58:17 +02:00
committed by GitHub
parent 8797a1441b
commit 678a06752a
45 changed files with 317 additions and 586 deletions
+6
View File
@@ -0,0 +1,6 @@
---
"medusa-react": patch
"@medusajs/medusa": patch
---
Finalise service migration and fix super constructor arguments
@@ -1,18 +1,18 @@
import { adminProductKeys } from "./queries" import { adminProductKeys } from "./queries"
import { import {
AdminProductsDeleteRes,
AdminProductsRes,
AdminPostProductsProductReq,
AdminPostProductsReq,
AdminPostProductsProductVariantsReq,
AdminProductsDeleteVariantRes,
AdminPostProductsProductOptionsReq,
AdminPostProductsProductOptionsOption, AdminPostProductsProductOptionsOption,
AdminPostProductsProductOptionsReq,
AdminPostProductsProductReq,
AdminPostProductsProductVariantsReq,
AdminPostProductsReq,
AdminProductsDeleteOptionRes, AdminProductsDeleteOptionRes,
AdminProductsDeleteRes,
AdminProductsDeleteVariantRes,
AdminProductsRes,
} from "@medusajs/medusa" } from "@medusajs/medusa"
import { Response } from "@medusajs/medusa-js" import { Response } from "@medusajs/medusa-js"
import { useMutation, UseMutationOptions, useQueryClient } from "react-query" import { useMutation, UseMutationOptions, useQueryClient } from "react-query"
import { useMedusa } from "../../../contexts/medusa" import { useMedusa } from "../../../contexts"
import { buildOptions } from "../../utils/buildOptions" import { buildOptions } from "../../utils/buildOptions"
export const useAdminCreateProduct = ( export const useAdminCreateProduct = (
@@ -89,5 +89,5 @@ export class AdminPostCustomerGroupsReq {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
} }
@@ -119,5 +119,5 @@ export class AdminPostCustomerGroupsGroupReq {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
} }
@@ -107,5 +107,5 @@ export class AdminPostDiscountsDiscountDynamicCodesReq {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
} }
@@ -440,7 +440,7 @@ export class AdminPostOrdersOrderClaimsReq {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
} }
class ReturnShipping { class ReturnShipping {
@@ -241,7 +241,7 @@ class Item {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
} }
class Image { class Image {
@@ -300,7 +300,7 @@ export class AdminPostProductsProductVariantsReq {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
@IsArray() @IsArray()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
@@ -307,7 +307,7 @@ export class AdminPostProductsProductVariantsVariantReq {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
@IsArray() @IsArray()
@IsOptional() @IsOptional()
@@ -219,7 +219,7 @@ export class AdminPostShippingOptionsReq {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
@FeatureFlagDecorators(TaxInclusivePricingFeatureFlag.key, [ @FeatureFlagDecorators(TaxInclusivePricingFeatureFlag.key, [
IsOptional(), IsOptional(),
@@ -178,7 +178,7 @@ export class AdminPostShippingOptionsOptionReq {
@IsObject() @IsObject()
@IsOptional() @IsOptional()
metadata?: object metadata?: Record<string, unknown>
@FeatureFlagDecorators(TaxInclusivePricingFeatureFlag.key, [ @FeatureFlagDecorators(TaxInclusivePricingFeatureFlag.key, [
IsOptional(), IsOptional(),
+2 -3
View File
@@ -1,6 +1,6 @@
import Scrypt from "scrypt-kdf" import Scrypt from "scrypt-kdf"
import { AuthenticateResult } from "../types/auth" import { AuthenticateResult } from "../types/auth"
import { User, Customer } from "../models" import { Customer, User } from "../models"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import UserService from "./user" import UserService from "./user"
import CustomerService from "./customer" import CustomerService from "./customer"
@@ -14,7 +14,6 @@ type InjectedDependencies = {
/** /**
* Can authenticate a user based on email password combination * Can authenticate a user based on email password combination
* @extends BaseService
*/ */
class AuthService extends TransactionBaseService { class AuthService extends TransactionBaseService {
protected manager_: EntityManager protected manager_: EntityManager
@@ -23,7 +22,7 @@ class AuthService extends TransactionBaseService {
protected readonly customerService_: CustomerService protected readonly customerService_: CustomerService
constructor({ manager, userService, customerService }: InjectedDependencies) { constructor({ manager, userService, customerService }: InjectedDependencies) {
super({ manager, userService, customerService }) super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.userService_ = userService this.userService_ = userService
+1 -6
View File
@@ -96,12 +96,7 @@ class BatchJobService extends TransactionBaseService {
eventBusService, eventBusService,
strategyResolverService, strategyResolverService,
}: InjectedDependencies) { }: InjectedDependencies) {
super({ super(arguments[0])
manager,
batchJobRepository,
eventBusService,
strategyResolverService,
})
this.manager_ = manager this.manager_ = manager
this.batchJobRepository_ = batchJobRepository this.batchJobRepository_ = batchJobRepository
+2 -2
View File
@@ -1,6 +1,6 @@
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { TransactionBaseService as BaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { ClaimImage, ClaimItem, ClaimTag } from "../models" import { ClaimImage, ClaimItem, ClaimTag } from "../models"
import { ClaimImageRepository } from "../repositories/claim-image" import { ClaimImageRepository } from "../repositories/claim-image"
import { ClaimItemRepository } from "../repositories/claim-item" import { ClaimItemRepository } from "../repositories/claim-item"
@@ -11,7 +11,7 @@ import { buildQuery, setMetadata } from "../utils"
import EventBusService from "./event-bus" import EventBusService from "./event-bus"
import LineItemService from "./line-item" import LineItemService from "./line-item"
class ClaimItemService extends BaseService { class ClaimItemService extends TransactionBaseService {
static Events = { static Events = {
CREATED: "claim_item.created", CREATED: "claim_item.created",
UPDATED: "claim_item.updated", UPDATED: "claim_item.updated",
+1 -1
View File
@@ -35,7 +35,7 @@ export default class CurrencyService extends TransactionBaseService {
eventBusService, eventBusService,
featureFlagRouter, featureFlagRouter,
}: InjectedDependencies) { }: InjectedDependencies) {
super({ manager }) super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.currencyRepository_ = currencyRepository this.currencyRepository_ = currencyRepository
this.eventBusService_ = eventBusService this.eventBusService_ = eventBusService
+47 -66
View File
@@ -1,5 +1,4 @@
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import { DeepPartial, EntityManager, ILike, SelectQueryBuilder } from "typeorm" import { DeepPartial, EntityManager, ILike, SelectQueryBuilder } from "typeorm"
import { CustomerService } from "." import { CustomerService } from "."
import { CustomerGroup } from ".." import { CustomerGroup } from ".."
@@ -9,7 +8,14 @@ import {
CustomerGroupUpdate, CustomerGroupUpdate,
FilterableCustomerGroupProps, FilterableCustomerGroupProps,
} from "../types/customer-groups" } from "../types/customer-groups"
import { isDefined, formatException, PostgresError } from "../utils" import {
buildQuery,
formatException,
isDefined,
PostgresError,
setMetadata,
} from "../utils"
import { TransactionBaseService } from "../interfaces"
type CustomerGroupConstructorProps = { type CustomerGroupConstructorProps = {
manager: EntityManager manager: EntityManager
@@ -17,55 +23,31 @@ type CustomerGroupConstructorProps = {
customerService: CustomerService customerService: CustomerService
} }
/** class CustomerGroupService extends TransactionBaseService {
* Provides layer to manipulate discounts. protected manager_: EntityManager
* @implements {BaseService} protected transactionManager_: EntityManager | undefined
*/
class CustomerGroupService extends BaseService {
private manager_: EntityManager
private customerGroupRepository_: typeof CustomerGroupRepository protected readonly customerGroupRepository_: typeof CustomerGroupRepository
protected readonly customerService_: CustomerService
private customerService_: CustomerService
constructor({ constructor({
manager, manager,
customerGroupRepository, customerGroupRepository,
customerService, customerService,
}: CustomerGroupConstructorProps) { }: CustomerGroupConstructorProps) {
super() super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.customerGroupRepository_ = customerGroupRepository this.customerGroupRepository_ = customerGroupRepository
/** @private @const {CustomerGroupService} */
this.customerService_ = customerService this.customerService_ = customerService
} }
withTransaction(transactionManager: EntityManager): CustomerGroupService {
if (!transactionManager) {
return this
}
const cloned = new CustomerGroupService({
manager: transactionManager,
customerGroupRepository: this.customerGroupRepository_,
customerService: this.customerService_,
})
cloned.transactionManager_ = transactionManager
return cloned
}
async retrieve(id: string, config = {}): Promise<CustomerGroup> { async retrieve(id: string, config = {}): Promise<CustomerGroup> {
const cgRepo = this.manager_.getCustomRepository( const cgRepo = this.manager_.getCustomRepository(
this.customerGroupRepository_ this.customerGroupRepository_
) )
const validatedId = this.validateId_(id) const query = buildQuery({ id }, config)
const query = this.buildQuery_({ id: validatedId }, config)
const customerGroup = await cgRepo.findOne(query) const customerGroup = await cgRepo.findOne(query)
if (!customerGroup) { if (!customerGroup) {
@@ -80,21 +62,18 @@ class CustomerGroupService extends BaseService {
/** /**
* Creates a customer group with the provided data. * Creates a customer group with the provided data.
* @param {DeepPartial<CustomerGroup>} group - the customer group to create * @param group - the customer group to create
* @return {Promise} the result of the create operation * @return the result of the create operation
*/ */
async create(group: DeepPartial<CustomerGroup>): Promise<CustomerGroup> { async create(group: DeepPartial<CustomerGroup>): Promise<CustomerGroup> {
return this.atomicPhase_(async (manager) => { return await this.atomicPhase_(async (manager) => {
try { try {
const cgRepo: CustomerGroupRepository = manager.getCustomRepository( const cgRepo: CustomerGroupRepository = manager.getCustomRepository(
this.customerGroupRepository_ this.customerGroupRepository_
) )
const created = cgRepo.create(group) const created = cgRepo.create(group)
return await cgRepo.save(created)
const result = await cgRepo.save(created)
return result
} catch (err) { } catch (err) {
if (err.code === PostgresError.DUPLICATE_ERROR) { if (err.code === PostgresError.DUPLICATE_ERROR) {
throw new MedusaError(MedusaError.Types.DUPLICATE_ERROR, err.detail) throw new MedusaError(MedusaError.Types.DUPLICATE_ERROR, err.detail)
@@ -106,9 +85,9 @@ class CustomerGroupService extends BaseService {
/** /**
* Add a batch of customers to a customer group at once * Add a batch of customers to a customer group at once
* @param {string} id id of the customer group to add customers to * @param id id of the customer group to add customers to
* @param {string[]} customerIds customer id's to add to the group * @param customerIds customer id's to add to the group
* @return {Promise<CustomerGroup>} the customer group after insertion * @return the customer group after insertion
*/ */
async addCustomers( async addCustomers(
id: string, id: string,
@@ -121,14 +100,14 @@ class CustomerGroupService extends BaseService {
ids = customerIds ids = customerIds
} }
return this.atomicPhase_( return await this.atomicPhase_(
async (manager) => { async (manager) => {
const cgRepo: CustomerGroupRepository = manager.getCustomRepository( const cgRepo: CustomerGroupRepository = manager.getCustomRepository(
this.customerGroupRepository_ this.customerGroupRepository_
) )
return await cgRepo.addCustomers(id, ids) return await cgRepo.addCustomers(id, ids)
}, },
async (error) => { async (error: any) => {
if (error.code === PostgresError.FOREIGN_KEY_ERROR) { if (error.code === PostgresError.FOREIGN_KEY_ERROR) {
await this.retrieve(id) await this.retrieve(id)
@@ -155,15 +134,15 @@ class CustomerGroupService extends BaseService {
/** /**
* Update a customer group. * Update a customer group.
* *
* @param {string} customerGroupId - id of the customer group * @param customerGroupId - id of the customer group
* @param {CustomerGroupUpdate} update - customer group partial data * @param update - customer group partial data
* @returns resulting customer group * @returns resulting customer group
*/ */
async update( async update(
customerGroupId: string, customerGroupId: string,
update: CustomerGroupUpdate update: CustomerGroupUpdate
): Promise<CustomerGroup[]> { ): Promise<CustomerGroup> {
return this.atomicPhase_(async (manager) => { return await this.atomicPhase_(async (manager) => {
const { metadata, ...properties } = update const { metadata, ...properties } = update
const cgRepo: CustomerGroupRepository = manager.getCustomRepository( const cgRepo: CustomerGroupRepository = manager.getCustomRepository(
@@ -179,8 +158,9 @@ class CustomerGroupService extends BaseService {
} }
if (isDefined(metadata)) { if (isDefined(metadata)) {
customerGroup.metadata = this.setMetadata_(customerGroup, metadata) customerGroup.metadata = setMetadata(customerGroup, metadata)
} }
return await cgRepo.save(customerGroup) return await cgRepo.save(customerGroup)
}) })
} }
@@ -188,11 +168,11 @@ class CustomerGroupService extends BaseService {
/** /**
* Remove customer group * Remove customer group
* *
* @param {string} groupId id of the customer group to delete * @param groupId id of the customer group to delete
* @return {Promise} a promise * @return a promise
*/ */
async delete(groupId: string): Promise<void> { async delete(groupId: string): Promise<void> {
return this.atomicPhase_(async (manager) => { return await this.atomicPhase_(async (manager) => {
const cgRepo: CustomerGroupRepository = manager.getCustomRepository( const cgRepo: CustomerGroupRepository = manager.getCustomRepository(
this.customerGroupRepository_ this.customerGroupRepository_
) )
@@ -210,9 +190,9 @@ class CustomerGroupService extends BaseService {
/** /**
* List customer groups. * List customer groups.
* *
* @param {Object} selector - the query object for find * @param selector - the query object for find
* @param {Object} config - the config to be used for find * @param config - the config to be used for find
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async list( async list(
selector: FilterableCustomerGroupProps = {}, selector: FilterableCustomerGroupProps = {},
@@ -222,16 +202,16 @@ class CustomerGroupService extends BaseService {
this.customerGroupRepository_ this.customerGroupRepository_
) )
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await cgRepo.find(query) return await cgRepo.find(query)
} }
/** /**
* Retrieve a list of customer groups and total count of records that match the query. * Retrieve a list of customer groups and total count of records that match the query.
* *
* @param {Object} selector - the query object for find * @param selector - the query object for find
* @param {Object} config - the config to be used for find * @param config - the config to be used for find
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async listAndCount( async listAndCount(
selector: FilterableCustomerGroupProps = {}, selector: FilterableCustomerGroupProps = {},
@@ -247,26 +227,27 @@ class CustomerGroupService extends BaseService {
delete selector.q delete selector.q
} }
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
if (q) { if (q) {
const where = query.where const where = query.where
delete where.name delete where.name
query.where = (qb: SelectQueryBuilder<CustomerGroup>): void => { query.where = ((qb: SelectQueryBuilder<CustomerGroup>): void => {
qb.where(where).andWhere([{ name: ILike(`%${q}%`) }]) qb.where(where).andWhere([{ name: ILike(`%${q}%`) }])
} }) as any
} }
return await cgRepo.findAndCount(query) return await cgRepo.findAndCount(query)
} }
/** /**
* Remove list of customers from a customergroup * Remove list of customers from a customergroup
* *
* @param {string} id id of the customer group from which the customers are removed * @param id id of the customer group from which the customers are removed
* @param {string[] | string} customerIds id's of the customer to remove from group * @param customerIds id's of the customer to remove from group
* @return {Promise<CustomerGroup>} the customergroup with the provided id * @return the customergroup with the provided id
*/ */
async removeCustomer( async removeCustomer(
id: string, id: string,
@@ -39,7 +39,7 @@ class DiscountConditionService extends TransactionBaseService {
discountConditionRepository, discountConditionRepository,
eventBusService, eventBusService,
}: InjectedDependencies) { }: InjectedDependencies) {
super({ manager, discountConditionRepository, eventBusService }) super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.discountConditionRepository_ = discountConditionRepository this.discountConditionRepository_ = discountConditionRepository
+2 -12
View File
@@ -8,7 +8,7 @@ import LineItemService from "./line-item"
import { OrderRepository } from "../repositories/order" import { OrderRepository } from "../repositories/order"
import ProductVariantService from "./product-variant" import ProductVariantService from "./product-variant"
import ShippingOptionService from "./shipping-option" import ShippingOptionService from "./shipping-option"
import { DraftOrder, DraftOrderStatus, Cart, CartType } from "../models" import { Cart, CartType, DraftOrder, DraftOrderStatus } from "../models"
import { AdminPostDraftOrdersReq } from "../api/routes/admin/draft-orders" import { AdminPostDraftOrdersReq } from "../api/routes/admin/draft-orders"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { ExtendedFindConfig, FindConfig } from "../types/common" import { ExtendedFindConfig, FindConfig } from "../types/common"
@@ -59,17 +59,7 @@ class DraftOrderService extends TransactionBaseService {
productVariantService, productVariantService,
shippingOptionService, shippingOptionService,
}: InjectedDependencies) { }: InjectedDependencies) {
super({ super(arguments[0])
manager,
draftOrderRepository,
paymentRepository,
orderRepository,
eventBusService,
cartService,
lineItemService,
productVariantService,
shippingOptionService,
})
this.manager_ = manager this.manager_ = manager
this.draftOrderRepository_ = draftOrderRepository this.draftOrderRepository_ = draftOrderRepository
+3 -2
View File
@@ -1,4 +1,3 @@
import { BaseService } from "medusa-interfaces"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
@@ -9,6 +8,7 @@ type InventoryServiceProps = {
manager: EntityManager manager: EntityManager
productVariantService: ProductVariantService productVariantService: ProductVariantService
} }
class InventoryService extends TransactionBaseService { class InventoryService extends TransactionBaseService {
protected readonly productVariantService_: ProductVariantService protected readonly productVariantService_: ProductVariantService
@@ -16,7 +16,7 @@ class InventoryService extends TransactionBaseService {
protected transactionManager_: EntityManager | undefined protected transactionManager_: EntityManager | undefined
constructor({ manager, productVariantService }: InventoryServiceProps) { constructor({ manager, productVariantService }: InventoryServiceProps) {
super({ manager, productVariantService }) super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.productVariantService_ = productVariantService this.productVariantService_ = productVariantService
@@ -52,6 +52,7 @@ class InventoryService extends TransactionBaseService {
} }
}) })
} }
/** /**
* Checks if the inventory of a variant can cover a given quantity. Will * Checks if the inventory of a variant can cover a given quantity. Will
* return true if the variant doesn't have managed inventory or if the variant * return true if the variant doesn't have managed inventory or if the variant
+24 -43
View File
@@ -1,6 +1,5 @@
import jwt, { JwtPayload } from "jsonwebtoken" import jwt, { JwtPayload } from "jsonwebtoken"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { EventBusService, UserService } from "." import { EventBusService, UserService } from "."
import { User } from ".." import { User } from ".."
@@ -9,6 +8,8 @@ import { InviteRepository } from "../repositories/invite"
import { UserRepository } from "../repositories/user" import { UserRepository } from "../repositories/user"
import { ListInvite } from "../types/invites" import { ListInvite } from "../types/invites"
import { ConfigModule } from "../types/global" import { ConfigModule } from "../types/global"
import { TransactionBaseService } from "../interfaces"
import { buildQuery } from "../utils"
// 7 days // 7 days
const DEFAULT_VALID_DURATION = 1000 * 60 * 60 * 24 * 7 const DEFAULT_VALID_DURATION = 1000 * 60 * 60 * 24 * 7
@@ -16,21 +17,23 @@ const DEFAULT_VALID_DURATION = 1000 * 60 * 60 * 24 * 7
type InviteServiceProps = { type InviteServiceProps = {
manager: EntityManager manager: EntityManager
userService: UserService userService: UserService
userRepository: UserRepository userRepository: typeof UserRepository
inviteRepository: InviteRepository inviteRepository: typeof InviteRepository
eventBusService: EventBusService eventBusService: EventBusService
} }
class InviteService extends BaseService { class InviteService extends TransactionBaseService {
static Events = { static Events = {
CREATED: "invite.created", CREATED: "invite.created",
} }
private manager_: EntityManager protected manager_: EntityManager
private userService_: UserService protected transactionManager_: EntityManager | undefined
private userRepo_: UserRepository
private inviteRepository_: InviteRepository protected readonly userService_: UserService
private eventBus_: EventBusService protected readonly userRepo_: typeof UserRepository
protected readonly inviteRepository_: typeof InviteRepository
protected readonly eventBus_: EventBusService
protected readonly configModule_: ConfigModule protected readonly configModule_: ConfigModule
@@ -44,7 +47,8 @@ class InviteService extends BaseService {
}: InviteServiceProps, }: InviteServiceProps,
configModule: ConfigModule configModule: ConfigModule
) { ) {
super() // @ts-ignore
super(...arguments)
this.configModule_ = configModule this.configModule_ = configModule
@@ -64,27 +68,6 @@ class InviteService extends BaseService {
this.eventBus_ = eventBusService this.eventBus_ = eventBusService
} }
withTransaction(manager): InviteService {
if (!manager) {
return this
}
const cloned = new InviteService(
{
manager,
inviteRepository: this.inviteRepository_,
userService: this.userService_,
userRepository: this.userRepo_,
eventBusService: this.eventBus_,
},
this.configModule_
)
cloned.transactionManager_ = manager
return cloned
}
generateToken(data): string { generateToken(data): string {
const { jwt_secret } = this.configModule_.projectConfig const { jwt_secret } = this.configModule_.projectConfig
if (jwt_secret) { if (jwt_secret) {
@@ -99,17 +82,17 @@ class InviteService extends BaseService {
async list(selector, config = {}): Promise<ListInvite[]> { async list(selector, config = {}): Promise<ListInvite[]> {
const inviteRepo = this.manager_.getCustomRepository(InviteRepository) const inviteRepo = this.manager_.getCustomRepository(InviteRepository)
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await inviteRepo.find(query) return await inviteRepo.find(query)
} }
/** /**
* Updates an account_user. * Updates an account_user.
* @param {string} user - user emails * @param user - user emails
* @param {string} role - role to assign to the user * @param role - role to assign to the user
* @param {number} validDuration - role to assign to the user * @param validDuration - role to assign to the user
* @return {Promise} the result of create * @return the result of create
*/ */
async create( async create(
user: string, user: string,
@@ -178,12 +161,12 @@ class InviteService extends BaseService {
/** /**
* Deletes an invite from a given user id. * Deletes an invite from a given user id.
* @param {string} inviteId - the id of the invite to delete. Must be * @param inviteId - the id of the invite to delete. Must be
* castable as an ObjectId * castable as an ObjectId
* @return {Promise} the result of the delete operation. * @return the result of the delete operation.
*/ */
async delete(inviteId): Promise<void> { async delete(inviteId): Promise<void> {
return this.atomicPhase_(async (manager) => { return await this.atomicPhase_(async (manager) => {
const inviteRepo: InviteRepository = const inviteRepo: InviteRepository =
manager.getCustomRepository(InviteRepository) manager.getCustomRepository(InviteRepository)
@@ -191,12 +174,10 @@ class InviteService extends BaseService {
const invite = await inviteRepo.findOne({ where: { id: inviteId } }) const invite = await inviteRepo.findOne({ where: { id: inviteId } })
if (!invite) { if (!invite) {
return Promise.resolve() return
} }
await inviteRepo.delete({ id: invite.id }) await inviteRepo.delete({ id: invite.id })
return Promise.resolve()
}) })
} }
@@ -213,7 +194,7 @@ class InviteService extends BaseService {
const { invite_id, user_email } = decoded const { invite_id, user_email } = decoded
return this.atomicPhase_(async (m) => { return await this.atomicPhase_(async (m) => {
const userRepo = m.getCustomRepository(this.userRepo_) const userRepo = m.getCustomRepository(this.userRepo_)
const inviteRepo: InviteRepository = m.getCustomRepository( const inviteRepo: InviteRepository = m.getCustomRepository(
this.inviteRepository_ this.inviteRepository_
@@ -33,7 +33,6 @@ type GeneratedAdjustment = {
/** /**
* Provides layer to manipulate line item adjustments. * Provides layer to manipulate line item adjustments.
* @extends BaseService
*/ */
class LineItemAdjustmentService extends TransactionBaseService { class LineItemAdjustmentService extends TransactionBaseService {
protected readonly manager_: EntityManager protected readonly manager_: EntityManager
+19 -45
View File
@@ -1,5 +1,4 @@
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import { EntityManager, In } from "typeorm" import { EntityManager, In } from "typeorm"
import { DeepPartial } from "typeorm/common/DeepPartial" import { DeepPartial } from "typeorm/common/DeepPartial"
@@ -18,7 +17,8 @@ import {
ProductVariantService, ProductVariantService,
RegionService, RegionService,
} from "./index" } from "./index"
import { setMetadata } from "../utils" import { buildQuery, setMetadata } from "../utils"
import { TransactionBaseService } from "../interfaces"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -33,12 +33,10 @@ type InjectedDependencies = {
featureFlagRouter: FlagRouter featureFlagRouter: FlagRouter
} }
/** class LineItemService extends TransactionBaseService {
* Provides layer to manipulate line items. protected manager_: EntityManager
* @extends BaseService protected transactionManager_: EntityManager | undefined
*/
class LineItemService extends BaseService {
protected readonly manager_: EntityManager
protected readonly lineItemRepository_: typeof LineItemRepository protected readonly lineItemRepository_: typeof LineItemRepository
protected readonly itemTaxLineRepo_: typeof LineItemTaxLineRepository protected readonly itemTaxLineRepo_: typeof LineItemTaxLineRepository
protected readonly cartRepository_: typeof CartRepository protected readonly cartRepository_: typeof CartRepository
@@ -61,7 +59,7 @@ class LineItemService extends BaseService {
lineItemAdjustmentService, lineItemAdjustmentService,
featureFlagRouter, featureFlagRouter,
}: InjectedDependencies) { }: InjectedDependencies) {
super() super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.lineItemRepository_ = lineItemRepository this.lineItemRepository_ = lineItemRepository
@@ -75,29 +73,6 @@ class LineItemService extends BaseService {
this.featureFlagRouter_ = featureFlagRouter this.featureFlagRouter_ = featureFlagRouter
} }
withTransaction(transactionManager: EntityManager): LineItemService {
if (!transactionManager) {
return this
}
const cloned = new LineItemService({
manager: transactionManager,
lineItemRepository: this.lineItemRepository_,
lineItemTaxLineRepository: this.itemTaxLineRepo_,
productVariantService: this.productVariantService_,
productService: this.productService_,
pricingService: this.pricingService_,
regionService: this.regionService_,
cartRepository: this.cartRepository_,
lineItemAdjustmentService: this.lineItemAdjustmentService_,
featureFlagRouter: this.featureFlagRouter_,
})
cloned.transactionManager_ = transactionManager
return cloned
}
async list( async list(
selector: Selector<LineItem>, selector: Selector<LineItem>,
config: FindConfig<LineItem> = { config: FindConfig<LineItem> = {
@@ -108,15 +83,15 @@ class LineItemService extends BaseService {
): Promise<LineItem[]> { ): Promise<LineItem[]> {
const manager = this.manager_ const manager = this.manager_
const lineItemRepo = manager.getCustomRepository(this.lineItemRepository_) const lineItemRepo = manager.getCustomRepository(this.lineItemRepository_)
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await lineItemRepo.find(query) return await lineItemRepo.find(query)
} }
/** /**
* Retrieves a line item by its id. * Retrieves a line item by its id.
* @param {string} id - the id of the line item to retrieve * @param id - the id of the line item to retrieve
* @param {object} config - the config to be used at query building * @param config - the config to be used at query building
* @return {Promise<LineItem | never>} the line item * @return the line item
*/ */
async retrieve(id: string, config = {}): Promise<LineItem | never> { async retrieve(id: string, config = {}): Promise<LineItem | never> {
const manager = this.manager_ const manager = this.manager_
@@ -124,8 +99,7 @@ class LineItemService extends BaseService {
this.lineItemRepository_ this.lineItemRepository_
) )
const validatedId = this.validateId_(id) const query = buildQuery({ id }, config)
const query = this.buildQuery_({ id: validatedId }, config)
const lineItem = await lineItemRepository.findOne(query) const lineItem = await lineItemRepository.findOne(query)
@@ -142,9 +116,9 @@ class LineItemService extends BaseService {
/** /**
* Creates return line items for a given cart based on the return items in a * Creates return line items for a given cart based on the return items in a
* return. * return.
* @param {string} returnId - the id to generate return items from. * @param returnId - the id to generate return items from.
* @param {string} cartId - the cart to assign the return line items to. * @param cartId - the cart to assign the return line items to.
* @return {Promise<LineItem[]>} the created line items * @return the created line items
*/ */
async createReturnLines( async createReturnLines(
returnId: string, returnId: string,
@@ -293,8 +267,8 @@ class LineItemService extends BaseService {
/** /**
* Create a line item * Create a line item
* @param {Partial<LineItem>} data - the line item object to create * @param data - the line item object to create
* @return {Promise<LineItem>} the created line item * @return the created line item
*/ */
async create(data: Partial<LineItem>): Promise<LineItem> { async create(data: Partial<LineItem>): Promise<LineItem> {
return await this.atomicPhase_( return await this.atomicPhase_(
@@ -361,8 +335,8 @@ class LineItemService extends BaseService {
/** /**
* Deletes a line item. * Deletes a line item.
* @param {string} id - the id of the line item to delete * @param id - the id of the line item to delete
* @return {Promise<LineItem | undefined>} the result of the delete operation * @return the result of the delete operation
*/ */
async delete(id: string): Promise<LineItem | undefined> { async delete(id: string): Promise<LineItem | undefined> {
return await this.atomicPhase_( return await this.atomicPhase_(
+1 -1
View File
@@ -31,7 +31,7 @@ class NoteService extends TransactionBaseService {
noteRepository, noteRepository,
eventBusService, eventBusService,
}: InjectedDependencies) { }: InjectedDependencies) {
super({ manager, noteRepository, eventBusService }) super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.noteRepository_ = noteRepository this.noteRepository_ = noteRepository
@@ -41,7 +41,6 @@ type PriceListConstructorProps = {
/** /**
* Provides layer to manipulate product tags. * Provides layer to manipulate product tags.
* @extends BaseService
*/ */
class PriceListService extends TransactionBaseService { class PriceListService extends TransactionBaseService {
protected manager_: EntityManager protected manager_: EntityManager
-1
View File
@@ -31,7 +31,6 @@ type InjectedDependencies = {
/** /**
* Allows retrieval of prices. * Allows retrieval of prices.
* @extends BaseService
*/ */
class PricingService extends TransactionBaseService { class PricingService extends TransactionBaseService {
protected manager_: EntityManager protected manager_: EntityManager
@@ -38,12 +38,7 @@ class ProductCollectionService extends TransactionBaseService {
productRepository, productRepository,
eventBusService, eventBusService,
}: InjectedDependencies) { }: InjectedDependencies) {
super({ super(arguments[0])
manager,
productCollectionRepository,
productRepository,
eventBusService,
})
this.manager_ = manager this.manager_ = manager
this.productCollectionRepository_ = productCollectionRepository this.productCollectionRepository_ = productCollectionRepository
+23 -39
View File
@@ -1,50 +1,34 @@
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import { EntityManager, ILike, SelectQueryBuilder } from "typeorm" import { EntityManager, ILike, SelectQueryBuilder } from "typeorm"
import { ProductTag } from "../models/product-tag" import { ProductTag } from "../models"
import { ProductTagRepository } from "../repositories/product-tag" import { ProductTagRepository } from "../repositories/product-tag"
import { FindConfig } from "../types/common" import { FindConfig } from "../types/common"
import { FilterableProductTagProps } from "../types/product" import { FilterableProductTagProps } from "../types/product"
import { TransactionBaseService } from "../interfaces"
import { buildQuery } from "../utils"
type ProductTagConstructorProps = { type ProductTagConstructorProps = {
manager: EntityManager manager: EntityManager
productTagRepository: typeof ProductTagRepository productTagRepository: typeof ProductTagRepository
} }
/** class ProductTagService extends TransactionBaseService {
* Provides layer to manipulate product tags. protected manager_: EntityManager
* @extends BaseService protected transactionManager_: EntityManager | undefined
*/
class ProductTagService extends BaseService { protected readonly tagRepo_: typeof ProductTagRepository
private manager_: EntityManager
private tagRepo_: typeof ProductTagRepository
constructor({ manager, productTagRepository }: ProductTagConstructorProps) { constructor({ manager, productTagRepository }: ProductTagConstructorProps) {
super() super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.tagRepo_ = productTagRepository this.tagRepo_ = productTagRepository
} }
withTransaction(transactionManager: EntityManager): ProductTagService {
if (!transactionManager) {
return this
}
const cloned = new ProductTagService({
manager: transactionManager,
productTagRepository: this.tagRepo_,
})
cloned.transactionManager_ = transactionManager
return cloned
}
/** /**
* Retrieves a product tag by id. * Retrieves a product tag by id.
* @param {string} tagId - the id of the product tag to retrieve * @param tagId - the id of the product tag to retrieve
* @param {Object} config - the config to retrieve the tag by * @param config - the config to retrieve the tag by
* @return {Promise<ProductTag>} the collection. * @return the collection.
*/ */
async retrieve( async retrieve(
tagId: string, tagId: string,
@@ -52,7 +36,7 @@ class ProductTagService extends BaseService {
): Promise<ProductTag> { ): Promise<ProductTag> {
const tagRepo = this.manager_.getCustomRepository(this.tagRepo_) const tagRepo = this.manager_.getCustomRepository(this.tagRepo_)
const query = this.buildQuery_({ id: tagId }, config) const query = buildQuery({ id: tagId }, config)
const tag = await tagRepo.findOne(query) const tag = await tagRepo.findOne(query)
if (!tag) { if (!tag) {
@@ -67,8 +51,8 @@ class ProductTagService extends BaseService {
/** /**
* Creates a product tag * Creates a product tag
* @param {object} tag - the product tag to create * @param tag - the product tag to create
* @return {Promise<ProductTag>} created product tag * @return created product tag
*/ */
async create(tag: Partial<ProductTag>): Promise<ProductTag> { async create(tag: Partial<ProductTag>): Promise<ProductTag> {
return await this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
@@ -81,9 +65,9 @@ class ProductTagService extends BaseService {
/** /**
* Lists product tags * Lists product tags
* @param {Object} selector - the query object for find * @param selector - the query object for find
* @param {Object} config - the config to be used for find * @param config - the config to be used for find
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async list( async list(
selector: FilterableProductTagProps = {}, selector: FilterableProductTagProps = {},
@@ -91,15 +75,15 @@ class ProductTagService extends BaseService {
): Promise<ProductTag[]> { ): Promise<ProductTag[]> {
const tagRepo = this.manager_.getCustomRepository(this.tagRepo_) const tagRepo = this.manager_.getCustomRepository(this.tagRepo_)
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await tagRepo.find(query) return await tagRepo.find(query)
} }
/** /**
* Lists product tags and adds count. * Lists product tags and adds count.
* @param {Object} selector - the query object for find * @param selector - the query object for find
* @param {Object} config - the config to be used for find * @param config - the config to be used for find
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async listAndCount( async listAndCount(
selector: FilterableProductTagProps = {}, selector: FilterableProductTagProps = {},
@@ -113,7 +97,7 @@ class ProductTagService extends BaseService {
delete selector.q delete selector.q
} }
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
if (q) { if (q) {
const where = query.where const where = query.where
@@ -1,47 +1,28 @@
import { BaseService } from "medusa-interfaces"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { ProductTaxRate } from "../models/product-tax-rate" import { ProductTaxRate } from "../models"
import { ProductTaxRateRepository } from "../repositories/product-tax-rate" import { ProductTaxRateRepository } from "../repositories/product-tax-rate"
import { FindConfig } from "../types/common" import { FindConfig } from "../types/common"
import { FilterableProductTaxRateProps } from "../types/product-tax-rate" import { FilterableProductTaxRateProps } from "../types/product-tax-rate"
import { TransactionBaseService } from "../interfaces"
import { buildQuery } from "../utils"
/** class ProductTaxRateService extends TransactionBaseService {
* Provides layer to manipulate product variants. protected manager_: EntityManager
* @extends BaseService protected transactionManager_: EntityManager | undefined
*/
class ProductTaxRateService extends BaseService { protected readonly productTaxRateRepository_: typeof ProductTaxRateRepository
private manager_: EntityManager
private productTaxRateRepository_: typeof ProductTaxRateRepository
constructor({ manager, productTaxRateRepository }) { constructor({ manager, productTaxRateRepository }) {
super() super(arguments[0])
/** @private @const {EntityManager} */
this.manager_ = manager this.manager_ = manager
/** @private @const {ProductVariantModel} */
this.productTaxRateRepository_ = productTaxRateRepository this.productTaxRateRepository_ = productTaxRateRepository
} }
withTransaction(transactionManager: EntityManager): ProductTaxRateService {
if (!transactionManager) {
return this
}
const cloned = new ProductTaxRateService({
manager: transactionManager,
productTaxRateRepository: this.productTaxRateRepository_,
})
cloned.transactionManager_ = transactionManager
return cloned
}
/** /**
* @param {FilterableProductVariantProps} selector - the query object for find * @param selector - the query object for find
* @param {FindConfig<ProductVariant>} config - query config object for variant retrieval * @param config - query config object for variant retrieval
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async list( async list(
selector: FilterableProductTaxRateProps, selector: FilterableProductTaxRateProps,
@@ -51,7 +32,7 @@ class ProductTaxRateService extends BaseService {
this.productTaxRateRepository_ this.productTaxRateRepository_
) )
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await pTaxRateRepo.find(query) return await pTaxRateRepo.find(query)
} }
+19 -35
View File
@@ -1,48 +1,32 @@
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import { EntityManager, ILike, SelectQueryBuilder } from "typeorm" import { EntityManager, ILike, SelectQueryBuilder } from "typeorm"
import { ProductType } from "../models/product-type" import { ProductType } from "../models/product-type"
import { ProductTypeRepository } from "../repositories/product-type" import { ProductTypeRepository } from "../repositories/product-type"
import { FindConfig } from "../types/common" import { FindConfig } from "../types/common"
import { FilterableProductTypeProps } from "../types/product" import { FilterableProductTypeProps } from "../types/product"
import { TransactionBaseService } from "../interfaces"
import { buildQuery } from "../utils"
class ProductTypeService extends TransactionBaseService {
protected manager_: EntityManager
protected transactionManager_: EntityManager | undefined
protected readonly typeRepository_: typeof ProductTypeRepository
/**
* Provides layer to manipulate products.
* @extends BaseService
*/
class ProductTypeService extends BaseService {
private manager_: EntityManager
private typeRepository_: typeof ProductTypeRepository
constructor({ manager, productTypeRepository }) { constructor({ manager, productTypeRepository }) {
super() super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.typeRepository_ = productTypeRepository this.typeRepository_ = productTypeRepository
} }
withTransaction(transactionManager: EntityManager): ProductTypeService {
if (!transactionManager) {
return this
}
const cloned = new ProductTypeService({
manager: transactionManager,
productTypeRepository: this.typeRepository_,
})
cloned.transactionManager_ = transactionManager
cloned.manager_ = transactionManager
return cloned
}
/** /**
* Gets a product by id. * Gets a product by id.
* Throws in case of DB Error and if product was not found. * Throws in case of DB Error and if product was not found.
* @param id - id of the product to get. * @param id - id of the product to get.
* @param config - object that defines what should be included in the * @param config - object that defines what should be included in the
* query response * query response
* @return {Promise<Product>} the result of the find one operation. * @return the result of the find one operation.
*/ */
async retrieve( async retrieve(
id: string, id: string,
@@ -50,7 +34,7 @@ class ProductTypeService extends BaseService {
): Promise<ProductType> { ): Promise<ProductType> {
const typeRepo = this.manager_.getCustomRepository(this.typeRepository_) const typeRepo = this.manager_.getCustomRepository(this.typeRepository_)
const query = this.buildQuery_({ id }, config) const query = buildQuery({ id }, config)
const type = await typeRepo.findOne(query) const type = await typeRepo.findOne(query)
if (!type) { if (!type) {
@@ -65,9 +49,9 @@ class ProductTypeService extends BaseService {
/** /**
* Lists product types * Lists product types
* @param {Object} selector - the query object for find * @param selector - the query object for find
* @param {Object} config - the config to be used for find * @param config - the config to be used for find
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async list( async list(
selector: FilterableProductTypeProps = {}, selector: FilterableProductTypeProps = {},
@@ -75,15 +59,15 @@ class ProductTypeService extends BaseService {
): Promise<ProductType[]> { ): Promise<ProductType[]> {
const typeRepo = this.manager_.getCustomRepository(this.typeRepository_) const typeRepo = this.manager_.getCustomRepository(this.typeRepository_)
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await typeRepo.find(query) return await typeRepo.find(query)
} }
/** /**
* Lists product tags and adds count. * Lists product tags and adds count.
* @param {Object} selector - the query object for find * @param selector - the query object for find
* @param {Object} config - the config to be used for find * @param config - the config to be used for find
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async listAndCount( async listAndCount(
selector: FilterableProductTypeProps = {}, selector: FilterableProductTypeProps = {},
@@ -97,7 +81,7 @@ class ProductTypeService extends BaseService {
delete selector.q delete selector.q
} }
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
if (q) { if (q) {
const where = query.where const where = query.where
+93 -164
View File
@@ -1,14 +1,16 @@
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import { Brackets, EntityManager, ILike, SelectQueryBuilder } from "typeorm" import { Brackets, EntityManager, ILike, SelectQueryBuilder } from "typeorm"
import { import {
IPriceSelectionStrategy, IPriceSelectionStrategy,
PriceSelectionContext, PriceSelectionContext,
} from "../interfaces/price-selection-strategy" TransactionBaseService,
import { MoneyAmount } from "../models/money-amount" } from "../interfaces"
import { Product } from "../models/product" import {
import { ProductOptionValue } from "../models/product-option-value" MoneyAmount,
import { ProductVariant } from "../models/product-variant" Product,
ProductOptionValue,
ProductVariant,
} from "../models"
import { CartRepository } from "../repositories/cart" import { CartRepository } from "../repositories/cart"
import { MoneyAmountRepository } from "../repositories/money-amount" import { MoneyAmountRepository } from "../repositories/money-amount"
import { ProductRepository } from "../repositories/product" import { ProductRepository } from "../repositories/product"
@@ -27,28 +29,26 @@ import {
ProductVariantPrice, ProductVariantPrice,
UpdateProductVariantInput, UpdateProductVariantInput,
} from "../types/product-variant" } from "../types/product-variant"
import { isDefined } from "../utils" import { buildQuery, isDefined, setMetadata } from "../utils"
/** class ProductVariantService extends TransactionBaseService {
* Provides layer to manipulate product variants.
* @extends BaseService
*/
class ProductVariantService extends BaseService {
static Events = { static Events = {
UPDATED: "product-variant.updated", UPDATED: "product-variant.updated",
CREATED: "product-variant.created", CREATED: "product-variant.created",
DELETED: "product-variant.deleted", DELETED: "product-variant.deleted",
} }
private manager_: EntityManager protected manager_: EntityManager
private productVariantRepository_: typeof ProductVariantRepository protected transactionManager_: EntityManager | undefined
private productRepository_: typeof ProductRepository
private eventBus_: EventBusService protected readonly productVariantRepository_: typeof ProductVariantRepository
private regionService_: RegionService protected readonly productRepository_: typeof ProductRepository
private priceSelectionStrategy_: IPriceSelectionStrategy protected readonly eventBus_: EventBusService
private moneyAmountRepository_: typeof MoneyAmountRepository protected readonly regionService_: RegionService
private productOptionValueRepository_: typeof ProductOptionValueRepository protected readonly priceSelectionStrategy_: IPriceSelectionStrategy
private cartRepository_: typeof CartRepository protected readonly moneyAmountRepository_: typeof MoneyAmountRepository
protected readonly productOptionValueRepository_: typeof ProductOptionValueRepository
protected readonly cartRepository_: typeof CartRepository
constructor({ constructor({
manager, manager,
@@ -61,59 +61,24 @@ class ProductVariantService extends BaseService {
cartRepository, cartRepository,
priceSelectionStrategy, priceSelectionStrategy,
}) { }) {
super() super(arguments[0])
/** @private @const {EntityManager} */
this.manager_ = manager this.manager_ = manager
/** @private @const {ProductVariantModel} */
this.productVariantRepository_ = productVariantRepository this.productVariantRepository_ = productVariantRepository
/** @private @const {ProductModel} */
this.productRepository_ = productRepository this.productRepository_ = productRepository
/** @private @const {EventBus} */
this.eventBus_ = eventBusService this.eventBus_ = eventBusService
/** @private @const {RegionService} */
this.regionService_ = regionService this.regionService_ = regionService
this.moneyAmountRepository_ = moneyAmountRepository this.moneyAmountRepository_ = moneyAmountRepository
this.productOptionValueRepository_ = productOptionValueRepository this.productOptionValueRepository_ = productOptionValueRepository
this.cartRepository_ = cartRepository this.cartRepository_ = cartRepository
this.priceSelectionStrategy_ = priceSelectionStrategy this.priceSelectionStrategy_ = priceSelectionStrategy
} }
withTransaction(transactionManager: EntityManager): ProductVariantService {
if (!transactionManager) {
return this
}
const cloned = new ProductVariantService({
manager: transactionManager,
productVariantRepository: this.productVariantRepository_,
productRepository: this.productRepository_,
eventBusService: this.eventBus_,
regionService: this.regionService_,
moneyAmountRepository: this.moneyAmountRepository_,
productOptionValueRepository: this.productOptionValueRepository_,
cartRepository: this.cartRepository_,
priceSelectionStrategy: this.priceSelectionStrategy_,
})
cloned.transactionManager_ = transactionManager
return cloned
}
/** /**
* Gets a product variant by id. * Gets a product variant by id.
* @param {string} variantId - the id of the product to get. * @param variantId - the id of the product to get.
* @param {FindConfig<ProductVariant>} config - query config object for variant retrieval. * @param config - query config object for variant retrieval.
* @return {Promise<Product>} the product document. * @return the product document.
*/ */
async retrieve( async retrieve(
variantId: string, variantId: string,
@@ -124,9 +89,7 @@ class ProductVariantService extends BaseService {
const variantRepo = this.manager_.getCustomRepository( const variantRepo = this.manager_.getCustomRepository(
this.productVariantRepository_ this.productVariantRepository_
) )
const validatedId = this.validateId_(variantId) const query = buildQuery({ id: variantId }, config)
const query = this.buildQuery_({ id: validatedId }, config)
const variant = await variantRepo.findOne(query) const variant = await variantRepo.findOne(query)
if (!variant) { if (!variant) {
@@ -141,9 +104,9 @@ class ProductVariantService extends BaseService {
/** /**
* Gets a product variant by id. * Gets a product variant by id.
* @param {string} sku - The unique stock keeping unit used to identify the product variant. * @param sku - The unique stock keeping unit used to identify the product variant.
* @param {FindConfig<ProductVariant>} config - query config object for variant retrieval. * @param config - query config object for variant retrieval.
* @return {Promise<Product>} the product document. * @return the product document.
*/ */
async retrieveBySKU( async retrieveBySKU(
sku: string, sku: string,
@@ -161,7 +124,7 @@ class ProductVariantService extends BaseService {
config.relations.splice(priceIndex, 1) config.relations.splice(priceIndex, 1)
} }
const query = this.buildQuery_({ sku }, config) const query = buildQuery({ sku }, config)
const variant = await variantRepo.findOne(query) const variant = await variantRepo.findOne(query)
if (!variant) { if (!variant) {
@@ -177,15 +140,15 @@ class ProductVariantService extends BaseService {
/** /**
* Creates an unpublished product variant. Will validate against parent product * Creates an unpublished product variant. Will validate against parent product
* to ensure that the variant can in fact be created. * to ensure that the variant can in fact be created.
* @param {string} productOrProductId - the product the variant will be added to * @param productOrProductId - the product the variant will be added to
* @param {object} variant - the variant to create * @param variant - the variant to create
* @return {Promise} resolves to the creation result. * @return resolves to the creation result.
*/ */
async create( async create(
productOrProductId: string | Product, productOrProductId: string | Product,
variant: CreateProductVariantInput variant: CreateProductVariantInput
): Promise<ProductVariant> { ): Promise<ProductVariant> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const productRepo = manager.getCustomRepository(this.productRepository_) const productRepo = manager.getCustomRepository(this.productRepository_)
const variantRepo = manager.getCustomRepository( const variantRepo = manager.getCustomRepository(
this.productVariantRepository_ this.productVariantRepository_
@@ -193,7 +156,7 @@ class ProductVariantService extends BaseService {
const { prices, ...rest } = variant const { prices, ...rest } = variant
let product = productOrProductId as Product let product = productOrProductId
if (typeof product === `string`) { if (typeof product === `string`) {
product = (await productRepo.findOne({ product = (await productRepo.findOne({
@@ -284,21 +247,21 @@ class ProductVariantService extends BaseService {
* Updates a variant. * Updates a variant.
* Price updates should use dedicated methods. * Price updates should use dedicated methods.
* The function will throw, if price updates are attempted. * The function will throw, if price updates are attempted.
* @param {string | ProductVariant} variantOrVariantId - variant or id of a variant. * @param variantOrVariantId - variant or id of a variant.
* @param {object} update - an object with the update values. * @param update - an object with the update values.
* @param {object} config - an object with the config values for returning the variant. * @param config - an object with the config values for returning the variant.
* @return {Promise} resolves to the update result. * @return resolves to the update result.
*/ */
async update( async update(
variantOrVariantId: string | Partial<ProductVariant>, variantOrVariantId: string | Partial<ProductVariant>,
update: UpdateProductVariantInput update: UpdateProductVariantInput
): Promise<ProductVariant> { ): Promise<ProductVariant> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const variantRepo = manager.getCustomRepository( const variantRepo = manager.getCustomRepository(
this.productVariantRepository_ this.productVariantRepository_
) )
let variant = variantOrVariantId as ProductVariant let variant = variantOrVariantId
if (typeof variant === `string`) { if (typeof variant === `string`) {
const variantRes = await variantRepo.findOne({ const variantRes = await variantRepo.findOne({
where: { id: variantOrVariantId as string }, where: { id: variantOrVariantId as string },
@@ -321,13 +284,13 @@ class ProductVariantService extends BaseService {
const { prices, options, metadata, inventory_quantity, ...rest } = update const { prices, options, metadata, inventory_quantity, ...rest } = update
if (prices) { if (prices) {
await this.updateVariantPrices(variant.id, prices) await this.updateVariantPrices(variant.id!, prices)
} }
if (options) { if (options) {
for (const option of options) { for (const option of options) {
await this.updateOptionValue( await this.updateOptionValue(
variant.id, variant.id!,
option.option_id, option.option_id,
option.value option.value
) )
@@ -335,7 +298,7 @@ class ProductVariantService extends BaseService {
} }
if (typeof metadata === "object") { if (typeof metadata === "object") {
variant.metadata = this.setMetadata_(variant, metadata as object) variant.metadata = setMetadata(variant as ProductVariant, metadata)
} }
if (typeof inventory_quantity === "number") { if (typeof inventory_quantity === "number") {
@@ -365,13 +328,13 @@ class ProductVariantService extends BaseService {
* Deletes any prices that are not in the update object, and is not associated with a price list. * Deletes any prices that are not in the update object, and is not associated with a price list.
* @param variantId - the id of variant * @param variantId - the id of variant
* @param prices - the update prices * @param prices - the update prices
* @returns {Promise<void>} empty promise * @returns empty promise
*/ */
async updateVariantPrices( async updateVariantPrices(
variantId: string, variantId: string,
prices: ProductVariantPrice[] prices: ProductVariantPrice[]
): Promise<void> { ): Promise<void> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const moneyAmountRepo = manager.getCustomRepository( const moneyAmountRepo = manager.getCustomRepository(
this.moneyAmountRepository_ this.moneyAmountRepository_
) )
@@ -404,15 +367,15 @@ class ProductVariantService extends BaseService {
* Gets the price specific to a region. If no region specific money amount * Gets the price specific to a region. If no region specific money amount
* exists the function will try to use a currency price. If no default * exists the function will try to use a currency price. If no default
* currency price exists the function will throw an error. * currency price exists the function will throw an error.
* @param {string} variantId - the id of the variant to get price from * @param variantId - the id of the variant to get price from
* @param {GetRegionPriceContext} context - context for getting region price * @param context - context for getting region price
* @return {number} the price specific to the region * @return the price specific to the region
*/ */
async getRegionPrice( async getRegionPrice(
variantId: string, variantId: string,
context: GetRegionPriceContext context: GetRegionPriceContext
): Promise<number> { ): Promise<number | null> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const region = await this.regionService_ const region = await this.regionService_
.withTransaction(manager) .withTransaction(manager)
.retrieve(context.regionId) .retrieve(context.regionId)
@@ -433,15 +396,15 @@ class ProductVariantService extends BaseService {
/** /**
* Sets the default price of a specific region * Sets the default price of a specific region
* @param {string} variantId - the id of the variant to update * @param variantId - the id of the variant to update
* @param {string} price - the price for the variant. * @param price - the price for the variant.
* @return {Promise} the result of the update operation * @return the result of the update operation
*/ */
async setRegionPrice( async setRegionPrice(
variantId: string, variantId: string,
price: ProductVariantPrice price: ProductVariantPrice
): Promise<MoneyAmount> { ): Promise<MoneyAmount> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const moneyAmountRepo = manager.getCustomRepository( const moneyAmountRepo = manager.getCustomRepository(
this.moneyAmountRepository_ this.moneyAmountRepository_
) )
@@ -463,22 +426,21 @@ class ProductVariantService extends BaseService {
moneyAmount.amount = price.amount moneyAmount.amount = price.amount
} }
const result = await moneyAmountRepo.save(moneyAmount) return await moneyAmountRepo.save(moneyAmount)
return result
}) })
} }
/** /**
* Sets the default price for the given currency. * Sets the default price for the given currency.
* @param {string} variantId - the id of the variant to set prices for * @param variantId - the id of the variant to set prices for
* @param {ProductVariantPrice} price - the price for the variant * @param price - the price for the variant
* @return {Promise} the result of the update operation * @return the result of the update operation
*/ */
async setCurrencyPrice( async setCurrencyPrice(
variantId: string, variantId: string,
price: ProductVariantPrice price: ProductVariantPrice
): Promise<MoneyAmount> { ): Promise<MoneyAmount> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const moneyAmountRepo = manager.getCustomRepository( const moneyAmountRepo = manager.getCustomRepository(
this.moneyAmountRepository_ this.moneyAmountRepository_
) )
@@ -490,17 +452,17 @@ class ProductVariantService extends BaseService {
/** /**
* Updates variant's option value. * Updates variant's option value.
* Option value must be of type string or number. * Option value must be of type string or number.
* @param {string} variantId - the variant to decorate. * @param variantId - the variant to decorate.
* @param {string} optionId - the option from product. * @param optionId - the option from product.
* @param {string} optionValue - option value to add. * @param optionValue - option value to add.
* @return {Promise} the result of the update operation. * @return the result of the update operation.
*/ */
async updateOptionValue( async updateOptionValue(
variantId: string, variantId: string,
optionId: string, optionId: string,
optionValue: string optionValue: string
): Promise<ProductOptionValue> { ): Promise<ProductOptionValue> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const productOptionValueRepo = manager.getCustomRepository( const productOptionValueRepo = manager.getCustomRepository(
this.productOptionValueRepository_ this.productOptionValueRepository_
) )
@@ -528,17 +490,17 @@ class ProductVariantService extends BaseService {
* if that product does not have an option with the given * if that product does not have an option with the given
* option id. Fails if given variant is not found. * option id. Fails if given variant is not found.
* Option value must be of type string or number. * Option value must be of type string or number.
* @param {string} variantId - the variant to decorate. * @param variantId - the variant to decorate.
* @param {string} optionId - the option from product. * @param optionId - the option from product.
* @param {string} optionValue - option value to add. * @param optionValue - option value to add.
* @return {Promise} the result of the update operation. * @return the result of the update operation.
*/ */
async addOptionValue( async addOptionValue(
variantId: string, variantId: string,
optionId: string, optionId: string,
optionValue: string optionValue: string
): Promise<ProductOptionValue> { ): Promise<ProductOptionValue> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const productOptionValueRepo = manager.getCustomRepository( const productOptionValueRepo = manager.getCustomRepository(
this.productOptionValueRepository_ this.productOptionValueRepository_
) )
@@ -556,12 +518,12 @@ class ProductVariantService extends BaseService {
/** /**
* Deletes option value from given variant. * Deletes option value from given variant.
* Will never fail due to delete being idempotent. * Will never fail due to delete being idempotent.
* @param {string} variantId - the variant to decorate. * @param variantId - the variant to decorate.
* @param {string} optionId - the option from product. * @param optionId - the option from product.
* @return {Promise} empty promise * @return empty promise
*/ */
async deleteOptionValue(variantId: string, optionId: string): Promise<void> { async deleteOptionValue(variantId: string, optionId: string): Promise<void> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const productOptionValueRepo: ProductOptionValueRepository = const productOptionValueRepo: ProductOptionValueRepository =
manager.getCustomRepository(this.productOptionValueRepository_) manager.getCustomRepository(this.productOptionValueRepository_)
@@ -583,9 +545,9 @@ class ProductVariantService extends BaseService {
} }
/** /**
* @param {object} selector - the query object for find * @param selector - the query object for find
* @param {FindConfig<ProductVariant>} config - query config object for variant retrieval * @param config - query config object for variant retrieval
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async listAndCount( async listAndCount(
selector: FilterableProductVariantProps, selector: FilterableProductVariantProps,
@@ -624,9 +586,9 @@ class ProductVariantService extends BaseService {
} }
/** /**
* @param {FilterableProductVariantProps} selector - the query object for find * @param selector - the query object for find
* @param {FindConfig<ProductVariant>} config - query config object for variant retrieval * @param config - query config object for variant retrieval
* @return {Promise} the result of the find operation * @return the result of the find operation
*/ */
async list( async list(
selector: FilterableProductVariantProps, selector: FilterableProductVariantProps,
@@ -652,7 +614,7 @@ class ProductVariantService extends BaseService {
delete selector.q delete selector.q
} }
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
if (q) { if (q) {
const where = query.where const where = query.where
@@ -682,12 +644,12 @@ class ProductVariantService extends BaseService {
/** /**
* Deletes variant. * Deletes variant.
* Will never fail due to delete being idempotent. * Will never fail due to delete being idempotent.
* @param {string} variantId - the id of the variant to delete. Must be * @param variantId - the id of the variant to delete. Must be
* castable as an ObjectId * castable as an ObjectId
* @return {Promise<void>} empty promise * @return empty promise
*/ */
async delete(variantId: string): Promise<void> { async delete(variantId: string): Promise<void> {
return this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const variantRepo = manager.getCustomRepository( const variantRepo = manager.getCustomRepository(
this.productVariantRepository_ this.productVariantRepository_
) )
@@ -710,47 +672,14 @@ class ProductVariantService extends BaseService {
product_id: variant.product_id, product_id: variant.product_id,
metadata: variant.metadata, metadata: variant.metadata,
}) })
return Promise.resolve()
}) })
} }
/**
* Dedicated method to set metadata for a variant.
* @param {string} variant - the variant to set metadata for.
* @param {Object} metadata - the metadata to set
* @return {Object} updated metadata object
*/
setMetadata_(
variant: ProductVariant,
metadata: object
): Record<string, unknown> {
const existing = variant.metadata || {}
const newData = {}
for (const [key, value] of Object.entries(metadata)) {
if (typeof key !== "string") {
throw new MedusaError(
MedusaError.Types.INVALID_ARGUMENT,
"Key type is invalid. Metadata keys must be strings"
)
}
newData[key] = value
}
const updated = {
...existing,
...newData,
}
return updated
}
/** /**
* Creates a query object to be used for list queries. * Creates a query object to be used for list queries.
* @param {object} selector - the selector to create the query from * @param selector - the selector to create the query from
* @param {object} config - the config to use for the query * @param config - the config to use for the query
* @return {object} an object containing the query, relations and free-text * @return an object containing the query, relations and free-text
* search param. * search param.
*/ */
prepareListQuery_( prepareListQuery_(
@@ -763,7 +692,7 @@ class ProductVariantService extends BaseService {
delete selector.q delete selector.q
} }
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
if (config.relations && config.relations.length > 0) { if (config.relations && config.relations.length > 0) {
query.relations = config.relations query.relations = config.relations
@@ -773,7 +702,7 @@ class ProductVariantService extends BaseService {
query.select = config.select query.select = config.select
} }
const rels = query.relations const rels = query.relations as string[]
delete query.relations delete query.relations
return { return {
@@ -786,10 +715,10 @@ class ProductVariantService extends BaseService {
/** /**
* Lists variants based on the provided parameters and includes the count of * Lists variants based on the provided parameters and includes the count of
* variants that match the query. * variants that match the query.
* @param {object} variantRepo - the variant repository * @param variantRepo - the variant repository
* @param {object} query - object that defines the scope for what should be returned * @param query - object that defines the scope for what should be returned
* @param {object} q - free text query * @param q - free text query
* @return {Promise<[ProductVariant[], number]>} an array containing the products as the first element and the total * @return an array containing the products as the first element and the total
* count of products that matches the query as the second element. * count of products that matches the query as the second element.
*/ */
getFreeTextQueryBuilder_( getFreeTextQueryBuilder_(
-1
View File
@@ -39,7 +39,6 @@ type InjectedDependencies = {
/** /**
* Provides layer to manipulate regions. * Provides layer to manipulate regions.
* @extends BaseService
*/ */
class RegionService extends TransactionBaseService { class RegionService extends TransactionBaseService {
static Events = { static Events = {
+1 -13
View File
@@ -74,19 +74,7 @@ class ReturnService extends TransactionBaseService {
inventoryService, inventoryService,
orderService, orderService,
}: InjectedDependencies) { }: InjectedDependencies) {
super({ super(arguments[0])
manager,
totalsService,
lineItemService,
returnRepository,
returnItemRepository,
shippingOptionService,
returnReasonService,
taxProviderService,
fulfillmentProviderService,
inventoryService,
orderService,
})
this.manager_ = manager this.manager_ = manager
this.totalsService_ = totalsService this.totalsService_ = totalsService
@@ -41,12 +41,7 @@ class SalesChannelService extends TransactionBaseService {
storeService, storeService,
}: InjectedDependencies) { }: InjectedDependencies) {
// eslint-disable-next-line prefer-rest-params // eslint-disable-next-line prefer-rest-params
super({ super(arguments[0])
salesChannelRepository,
eventBusService,
manager,
storeService,
})
this.manager_ = manager this.manager_ = manager
this.salesChannelRepository_ = salesChannelRepository this.salesChannelRepository_ = salesChannelRepository
@@ -27,6 +27,7 @@ type InjectedDependencies = {
shippingProfileRepository: typeof ShippingProfileRepository shippingProfileRepository: typeof ShippingProfileRepository
productRepository: typeof ProductRepository productRepository: typeof ProductRepository
} }
/** /**
* Provides layer to manipulate profiles. * Provides layer to manipulate profiles.
* @constructor * @constructor
@@ -51,14 +52,7 @@ class ShippingProfileService extends TransactionBaseService {
shippingOptionService, shippingOptionService,
customShippingOptionService, customShippingOptionService,
}: InjectedDependencies) { }: InjectedDependencies) {
super({ super(arguments[0])
manager,
shippingProfileRepository,
productService,
productRepository,
shippingOptionService,
customShippingOptionService,
})
this.manager_ = manager this.manager_ = manager
this.shippingProfileRepository_ = shippingProfileRepository this.shippingProfileRepository_ = shippingProfileRepository
@@ -1,43 +1,24 @@
import { BaseService } from "medusa-interfaces"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { ShippingTaxRate } from "../models/shipping-tax-rate" import { ShippingTaxRate } from "../models"
import { ShippingTaxRateRepository } from "../repositories/shipping-tax-rate" import { ShippingTaxRateRepository } from "../repositories/shipping-tax-rate"
import { FindConfig } from "../types/common" import { FindConfig } from "../types/common"
import { FilterableShippingTaxRateProps } from "../types/shipping-tax-rate" import { FilterableShippingTaxRateProps } from "../types/shipping-tax-rate"
import { TransactionBaseService } from "../interfaces"
import { buildQuery } from "../utils"
/** class ShippingTaxRateService extends TransactionBaseService {
* Provides layer to manipulate Shipping variants. protected manager_: EntityManager
* @extends BaseService protected transactionManager_: EntityManager | undefined
*/
class ShippingTaxRateService extends BaseService { protected readonly shippingTaxRateRepository_: typeof ShippingTaxRateRepository
private manager_: EntityManager
private shippingTaxRateRepository_: typeof ShippingTaxRateRepository
constructor({ manager, shippingTaxRateRepository }) { constructor({ manager, shippingTaxRateRepository }) {
super() super(arguments[0])
/** @private @const {EntityManager} */
this.manager_ = manager this.manager_ = manager
/** @private @const {ShippingVariantModel} */
this.shippingTaxRateRepository_ = shippingTaxRateRepository this.shippingTaxRateRepository_ = shippingTaxRateRepository
} }
withTransaction(transactionManager: EntityManager): ShippingTaxRateService {
if (!transactionManager) {
return this
}
const cloned = new ShippingTaxRateService({
manager: transactionManager,
shippingTaxRateRepository: this.ShippingTaxRateRepository_,
})
cloned.transactionManager_ = transactionManager
return cloned
}
/** /**
* Lists Shipping Tax Rates given a certain query. * Lists Shipping Tax Rates given a certain query.
* @param selector - the query object for find * @param selector - the query object for find
@@ -52,7 +33,7 @@ class ShippingTaxRateService extends BaseService {
this.shippingTaxRateRepository_ this.shippingTaxRateRepository_
) )
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await sTaxRateRepo.find(query) return await sTaxRateRepo.find(query)
} }
-1
View File
@@ -19,7 +19,6 @@ type InjectedDependencies = {
/** /**
* Provides layer to manipulate store settings. * Provides layer to manipulate store settings.
* @extends BaseService
*/ */
class StoreService extends TransactionBaseService { class StoreService extends TransactionBaseService {
protected manager_: EntityManager protected manager_: EntityManager
+18 -34
View File
@@ -1,5 +1,4 @@
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { ProductTaxRate } from "../models/product-tax-rate" import { ProductTaxRate } from "../models/product-tax-rate"
import { ProductTypeTaxRate } from "../models/product-type-tax-rate" import { ProductTypeTaxRate } from "../models/product-type-tax-rate"
@@ -16,14 +15,18 @@ import {
TaxRateListByConfig, TaxRateListByConfig,
UpdateTaxRateInput, UpdateTaxRateInput,
} from "../types/tax-rate" } from "../types/tax-rate"
import { isDefined, PostgresError } from "../utils" import { buildQuery, isDefined, PostgresError } from "../utils"
import { TransactionBaseService } from "../interfaces"
import { FindConditions } from "typeorm/find-options/FindConditions"
class TaxRateService extends BaseService { class TaxRateService extends TransactionBaseService {
private manager_: EntityManager protected manager_: EntityManager
private productService_: ProductService protected transactionManager_: EntityManager | undefined
private productTypeService_: ProductTypeService
private shippingOptionService_: ShippingOptionService protected readonly productService_: ProductService
private taxRateRepository_: typeof TaxRateRepository protected readonly productTypeService_: ProductTypeService
protected readonly shippingOptionService_: ShippingOptionService
protected readonly taxRateRepository_: typeof TaxRateRepository
constructor({ constructor({
manager, manager,
@@ -32,7 +35,7 @@ class TaxRateService extends BaseService {
shippingOptionService, shippingOptionService,
taxRateRepository, taxRateRepository,
}) { }) {
super() super(arguments[0])
this.manager_ = manager this.manager_ = manager
this.taxRateRepository_ = taxRateRepository this.taxRateRepository_ = taxRateRepository
@@ -41,25 +44,6 @@ class TaxRateService extends BaseService {
this.shippingOptionService_ = shippingOptionService this.shippingOptionService_ = shippingOptionService
} }
withTransaction(transactionManager: EntityManager): TaxRateService {
if (!transactionManager) {
return this
}
const cloned = new TaxRateService({
manager: transactionManager,
taxRateRepository: this.taxRateRepository_,
productService: this.productService_,
productTypeService: this.productTypeService_,
shippingOptionService: this.shippingOptionService_,
})
cloned.transactionManager_ = transactionManager
cloned.manager_ = transactionManager
return cloned
}
async list( async list(
selector: FilterableTaxRateProps, selector: FilterableTaxRateProps,
config: FindConfig<TaxRate> = {} config: FindConfig<TaxRate> = {}
@@ -67,7 +51,7 @@ class TaxRateService extends BaseService {
const taxRateRepo = this.manager_.getCustomRepository( const taxRateRepo = this.manager_.getCustomRepository(
this.taxRateRepository_ this.taxRateRepository_
) )
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await taxRateRepo.findWithResolution(query) return await taxRateRepo.findWithResolution(query)
} }
@@ -78,7 +62,7 @@ class TaxRateService extends BaseService {
const taxRateRepo = this.manager_.getCustomRepository( const taxRateRepo = this.manager_.getCustomRepository(
this.taxRateRepository_ this.taxRateRepository_
) )
const query = this.buildQuery_(selector, config) const query = buildQuery(selector, config)
return await taxRateRepo.findAndCountWithResolution(query) return await taxRateRepo.findAndCountWithResolution(query)
} }
@@ -88,7 +72,7 @@ class TaxRateService extends BaseService {
): Promise<TaxRate> { ): Promise<TaxRate> {
const manager = this.manager_ const manager = this.manager_
const taxRateRepo = manager.getCustomRepository(this.taxRateRepository_) const taxRateRepo = manager.getCustomRepository(this.taxRateRepository_)
const query = this.buildQuery_({ id }, config) const query = buildQuery({ id }, config)
const taxRate = await taxRateRepo.findOneWithResolution(query) const taxRate = await taxRateRepo.findOneWithResolution(query)
if (!taxRate) { if (!taxRate) {
@@ -135,8 +119,8 @@ class TaxRateService extends BaseService {
async delete(id: string | string[]): Promise<void> { async delete(id: string | string[]): Promise<void> {
return await this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const taxRateRepo = manager.getCustomRepository(this.taxRateRepository_) const taxRateRepo = manager.getCustomRepository(this.taxRateRepository_)
const query = this.buildQuery_({ id }) const query = buildQuery({ id })
await taxRateRepo.delete(query.where) await taxRateRepo.delete(query.where as FindConditions<TaxRate>)
}) })
} }
@@ -274,7 +258,7 @@ class TaxRateService extends BaseService {
id: string, id: string,
optionIds: string | string[], optionIds: string | string[],
replace = false replace = false
): Promise<ShippingTaxRate> { ): Promise<ShippingTaxRate[]> {
let ids: string[] let ids: string[]
if (typeof optionIds === "string") { if (typeof optionIds === "string") {
ids = [optionIds] ids = [optionIds]
+1 -6
View File
@@ -111,12 +111,7 @@ class TotalsService extends TransactionBaseService {
taxCalculationStrategy, taxCalculationStrategy,
featureFlagRouter, featureFlagRouter,
}: TotalsServiceProps) { }: TotalsServiceProps) {
super({ super(arguments[0])
taxProviderService,
taxCalculationStrategy,
manager,
featureFlagRouter,
})
this.manager_ = manager this.manager_ = manager
this.taxProviderService_ = taxProviderService this.taxProviderService_ = taxProviderService
-1
View File
@@ -23,7 +23,6 @@ type UserServiceProps = {
/** /**
* Provides layer to manipulate users. * Provides layer to manipulate users.
* @extends BaseService
*/ */
class UserService extends TransactionBaseService { class UserService extends TransactionBaseService {
static Events = { static Events = {
+1 -1
View File
@@ -54,7 +54,7 @@ export type CartCreateProps = {
customer_id?: string customer_id?: string
type?: CartType type?: CartType
context?: object context?: object
metadata?: object metadata?: Record<string, unknown>
sales_channel_id?: string sales_channel_id?: string
country_code?: string country_code?: string
} }
+2 -2
View File
@@ -14,7 +14,7 @@ export type CreateClaimInput = {
refund_amount?: number refund_amount?: number
shipping_address?: AddressPayload shipping_address?: AddressPayload
no_notification?: boolean no_notification?: boolean
metadata?: object metadata?: Record<string, unknown>
order: Order order: Order
claim_order_id?: string claim_order_id?: string
shipping_address_id?: string shipping_address_id?: string
@@ -67,7 +67,7 @@ type UpdateClaimItemInput = {
reason?: string reason?: string
images: UpdateClaimItemImageInput[] images: UpdateClaimItemImageInput[]
tags: UpdateClaimItemTagInput[] tags: UpdateClaimItemTagInput[]
metadata?: object metadata?: Record<string, unknown>
} }
type UpdateClaimItemImageInput = { type UpdateClaimItemImageInput = {
+1 -1
View File
@@ -37,5 +37,5 @@ export class CustomerGroupsBatchCustomer {
export class CustomerGroupUpdate { export class CustomerGroupUpdate {
name?: string name?: string
metadata?: object metadata?: Record<string, unknown>
} }
+1 -1
View File
@@ -161,5 +161,5 @@ export type CreateDynamicDiscountInput = {
code: string code: string
ends_at?: Date ends_at?: Date
usage_limit: number usage_limit: number
metadata?: object metadata?: Record<string, unknown>
} }
+2 -2
View File
@@ -57,7 +57,7 @@ export type CreateProductVariantInput = {
width?: number width?: number
options: ProductVariantOption[] options: ProductVariantOption[]
prices: ProductVariantPrice[] prices: ProductVariantPrice[]
metadata?: object metadata?: Record<string, unknown>
} }
export type UpdateProductVariantInput = { export type UpdateProductVariantInput = {
@@ -81,7 +81,7 @@ export type UpdateProductVariantInput = {
width?: number width?: number
options?: ProductVariantOption[] options?: ProductVariantOption[]
prices?: ProductVariantPrice[] prices?: ProductVariantPrice[]
metadata?: object metadata?: Record<string, unknown>
} }
export class FilterableProductVariantProps { export class FilterableProductVariantProps {
+2 -2
View File
@@ -197,7 +197,7 @@ export type CreateProductProductVariantInput = {
origin_country?: string origin_country?: string
mid_code?: string mid_code?: string
material?: string material?: string
metadata?: object metadata?: Record<string, unknown>
prices?: CreateProductProductVariantPriceInput[] prices?: CreateProductProductVariantPriceInput[]
options?: { value: string }[] options?: { value: string }[]
} }
@@ -220,7 +220,7 @@ export type UpdateProductProductVariantDTO = {
origin_country?: string origin_country?: string
mid_code?: string mid_code?: string
material?: string material?: string
metadata?: object metadata?: Record<string, unknown>
prices?: CreateProductProductVariantPriceInput[] prices?: CreateProductProductVariantPriceInput[]
options?: { value: string; option_id: string }[] options?: { value: string; option_id: string }[]
} }