chore: initial commit fix linting issues (#2169)

* chore: lint fixes
This commit is contained in:
Carlos R. L. Rodrigues authored and GitHub committed 2022-09-21 12:19:03 -03:00
1 parent c661cc789b
commit eb8034502b
118 files changed
+535 -431

No files matched your search

@@ -36,9 +36,9 @@ class AlgoliaService extends SearchService {
* @param {string} indexName - the index name. * @param {string} indexName - the index name.
* @return {Promise<{object}>} - returns response from search engine provider * @return {Promise<{object}>} - returns response from search engine provider
*/ */
getIndex(indexName) { async getIndex(indexName) {
let hits = [] let hits = []
return this.client_ return await this.client_
.initIndex(indexName) .initIndex(indexName)
.browseObjects({ .browseObjects({
query: indexName, query: indexName,
@@ -56,9 +56,11 @@ class AlgoliaService extends SearchService {
* @param {*} type * @param {*} type
* @return {*} * @return {*}
*/ */
addDocuments(indexName, documents, type) { async addDocuments(indexName, documents, type) {
const transformedDocuments = this.getTransformedDocuments(type, documents) const transformedDocuments = this.getTransformedDocuments(type, documents)
return this.client_.initIndex(indexName).saveObjects(transformedDocuments) return await this.client_
.initIndex(indexName)
.saveObjects(transformedDocuments)
} }
/** /**
@@ -68,9 +70,9 @@ class AlgoliaService extends SearchService {
* @param {Array.<Object>} type - type of documents to be replaced (e.g: products, regions, orders, etc) * @param {Array.<Object>} type - type of documents to be replaced (e.g: products, regions, orders, etc)
* @return {Promise<{object}>} - returns response from search engine provider * @return {Promise<{object}>} - returns response from search engine provider
*/ */
replaceDocuments(indexName, documents, type) { async replaceDocuments(indexName, documents, type) {
const transformedDocuments = this.getTransformedDocuments(type, documents) const transformedDocuments = this.getTransformedDocuments(type, documents)
return this.client_ return await this.client_
.initIndex(indexName) .initIndex(indexName)
.replaceAllObjects(transformedDocuments) .replaceAllObjects(transformedDocuments)
} }
@@ -81,8 +83,8 @@ class AlgoliaService extends SearchService {
* @param {string} document_id - the id of the document * @param {string} document_id - the id of the document
* @return {Promise<{object}>} - returns response from search engine provider * @return {Promise<{object}>} - returns response from search engine provider
*/ */
deleteDocument(indexName, document_id) { async deleteDocument(indexName, document_id) {
return this.client_.initIndex(indexName).deleteObject(document_id) return await this.client_.initIndex(indexName).deleteObject(document_id)
} }
/** /**
@@ -90,8 +92,8 @@ class AlgoliaService extends SearchService {
* @param {string} indexName - the index name * @param {string} indexName - the index name
* @return {Promise<{object}>} - returns response from search engine provider * @return {Promise<{object}>} - returns response from search engine provider
*/ */
deleteAllDocuments(indexName) { async deleteAllDocuments(indexName) {
return this.client_.initIndex(indexName).delete() return await this.client_.initIndex(indexName).delete()
} }
/** /**
@@ -103,14 +105,14 @@ class AlgoliaService extends SearchService {
* - additionalOptions contain any provider specific options * - additionalOptions contain any provider specific options
* @return {*} - returns response from search engine provider * @return {*} - returns response from search engine provider
*/ */
search(indexName, query, options) { async search(indexName, query, options) {
const { paginationOptions, filter, additionalOptions } = options const { paginationOptions, filter, additionalOptions } = options
if ("limit" in paginationOptions) { if ("limit" in paginationOptions) {
paginationOptions["length"] = paginationOptions.limit paginationOptions["length"] = paginationOptions.limit
delete paginationOptions.limit delete paginationOptions.limit
} }
return this.client_.initIndex(indexName).search(query, { return await this.client_.initIndex(indexName).search(query, {
filters: filter, filters: filter,
...paginationOptions, ...paginationOptions,
...additionalOptions, ...additionalOptions,
@@ -123,8 +125,8 @@ class AlgoliaService extends SearchService {
* @param {object} settings - settings object * @param {object} settings - settings object
* @return {Promise<{object}>} - returns response from search engine provider * @return {Promise<{object}>} - returns response from search engine provider
*/ */
updateSettings(indexName, settings) { async updateSettings(indexName, settings) {
return this.client_.initIndex(indexName).setSettings(settings) return await this.client_.initIndex(indexName).setSettings(settings)
} }
getTransformedDocuments(type, documents) { getTransformedDocuments(type, documents) {
@@ -12,41 +12,45 @@ class MeiliSearchService extends SearchService {
this.client_ = new MeiliSearch(options.config) this.client_ = new MeiliSearch(options.config)
} }
createIndex(indexName, options) { async createIndex(indexName, options) {
return this.client_.createIndex(indexName, options) return await this.client_.createIndex(indexName, options)
} }
getIndex(indexName) { getIndex(indexName) {
return this.client_.index(indexName) return this.client_.index(indexName)
} }
addDocuments(indexName, documents, type) { async addDocuments(indexName, documents, type) {
const transformedDocuments = this.getTransformedDocuments(type, documents) const transformedDocuments = this.getTransformedDocuments(type, documents)
return this.client_.index(indexName).addDocuments(transformedDocuments) return await this.client_
.index(indexName)
.addDocuments(transformedDocuments)
} }
replaceDocuments(indexName, documents, type) { async replaceDocuments(indexName, documents, type) {
const transformedDocuments = this.getTransformedDocuments(type, documents) const transformedDocuments = this.getTransformedDocuments(type, documents)
return this.client_.index(indexName).addDocuments(transformedDocuments) return await this.client_
.index(indexName)
.addDocuments(transformedDocuments)
} }
deleteDocument(indexName, document_id) { async deleteDocument(indexName, document_id) {
return this.client_.index(indexName).deleteDocument(document_id) return await this.client_.index(indexName).deleteDocument(document_id)
} }
deleteAllDocuments(indexName) { async deleteAllDocuments(indexName) {
return this.client_.index(indexName).deleteAllDocuments() return await this.client_.index(indexName).deleteAllDocuments()
} }
search(indexName, query, options) { async search(indexName, query, options) {
const { paginationOptions, filter, additionalOptions } = options const { paginationOptions, filter, additionalOptions } = options
return this.client_ return await this.client_
.index(indexName) .index(indexName)
.search(query, { filter, ...paginationOptions, ...additionalOptions }) .search(query, { filter, ...paginationOptions, ...additionalOptions })
} }
updateSettings(indexName, settings) { async updateSettings(indexName, settings) {
return this.client_.index(indexName).updateSettings(settings) return await this.client_.index(indexName).updateSettings(settings)
} }
getTransformedDocuments(type, documents) { getTransformedDocuments(type, documents) {
+1 -1
View File
@@ -1,3 +1,3 @@
global.afterEach(async () => { global.afterEach(async () => {
await new Promise(resolve => setImmediate(resolve)) await new Promise((resolve) => setImmediate(resolve))
}) })
@@ -1,7 +1,7 @@
import { IsEmail, IsNotEmpty, IsString } from "class-validator" import { IsEmail, IsNotEmpty, IsString } from "class-validator"
import AuthService from "../../../../services/auth" import AuthService from "../../../../services/auth"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import _ from "lodash" import _ from "lodash"
import jwt from "jsonwebtoken" import jwt from "jsonwebtoken"
@@ -78,7 +78,9 @@ import { validator } from "../../../../utils/validator"
* $ref: "#/components/responses/500_error" * $ref: "#/components/responses/500_error"
*/ */
export default async (req, res) => { export default async (req, res) => {
const { projectConfig: { jwt_secret } } = req.scope.resolve('configModule') const {
projectConfig: { jwt_secret },
} = req.scope.resolve("configModule")
if (!jwt_secret) { if (!jwt_secret) {
throw new MedusaError( throw new MedusaError(
MedusaError.Types.NOT_FOUND, MedusaError.Types.NOT_FOUND,
@@ -90,10 +92,9 @@ export default async (req, res) => {
const authService: AuthService = req.scope.resolve("authService") const authService: AuthService = req.scope.resolve("authService")
const manager: EntityManager = req.scope.resolve("manager") const manager: EntityManager = req.scope.resolve("manager")
const result = await manager.transaction(async (transactionManager) => { const result = await manager.transaction(async (transactionManager) => {
return await authService.withTransaction(transactionManager).authenticate( return await authService
validated.email, .withTransaction(transactionManager)
validated.password .authenticate(validated.email, validated.password)
)
}) })
if (result.success && result.user) { if (result.success && result.user) {
@@ -320,27 +320,37 @@ export class AdminGetBatchParams extends AdminGetBatchPaginationParams {
type?: string[] type?: string[]
@IsOptional() @IsOptional()
@Transform(({ value }) => (value === "null" ? null : value)) @Transform(({ value }) => {
return value === "null" ? null : value
})
@Type(() => DateComparisonOperator) @Type(() => DateComparisonOperator)
confirmed_at?: DateComparisonOperator | null confirmed_at?: DateComparisonOperator | null
@IsOptional() @IsOptional()
@Transform(({ value }) => (value === "null" ? null : value)) @Transform(({ value }) => {
return value === "null" ? null : value
})
@Type(() => DateComparisonOperator) @Type(() => DateComparisonOperator)
pre_processed_at?: DateComparisonOperator | null pre_processed_at?: DateComparisonOperator | null
@IsOptional() @IsOptional()
@Transform(({ value }) => (value === "null" ? null : value)) @Transform(({ value }) => {
return value === "null" ? null : value
})
@Type(() => DateComparisonOperator) @Type(() => DateComparisonOperator)
completed_at?: DateComparisonOperator | null completed_at?: DateComparisonOperator | null
@IsOptional() @IsOptional()
@Transform(({ value }) => (value === "null" ? null : value)) @Transform(({ value }) => {
return value === "null" ? null : value
})
@Type(() => DateComparisonOperator) @Type(() => DateComparisonOperator)
failed_at?: DateComparisonOperator | null failed_at?: DateComparisonOperator | null
@IsOptional() @IsOptional()
@Transform(({ value }) => (value === "null" ? null : value)) @Transform(({ value }) => {
return value === "null" ? null : value
})
@Type(() => DateComparisonOperator) @Type(() => DateComparisonOperator)
canceled_at?: DateComparisonOperator | null canceled_at?: DateComparisonOperator | null
@@ -1,6 +1,6 @@
import { Request, Response } from "express" import { Request, Response } from "express"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
import ProductCollectionService from "../../../../services/product-collection" import ProductCollectionService from "../../../../services/product-collection"
/** /**
@@ -72,10 +72,11 @@ export default async (req: Request, res: Response) => {
const manager: EntityManager = req.scope.resolve("manager") const manager: EntityManager = req.scope.resolve("manager")
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
return await productCollectionService.withTransaction(transactionManager).delete(id) return await productCollectionService
.withTransaction(transactionManager)
.delete(id)
}) })
res.json({ res.json({
id, id,
object: "product-collection", object: "product-collection",
@@ -2,7 +2,10 @@ import { Router } from "express"
import "reflect-metadata" import "reflect-metadata"
import { ProductCollection } from "../../../.." import { ProductCollection } from "../../../.."
import { DeleteResponse, PaginatedResponse } from "../../../../types/common" import { DeleteResponse, PaginatedResponse } from "../../../../types/common"
import middlewares, { transformBody, transformQuery } from "../../../middlewares" import middlewares, {
transformBody,
transformQuery,
} from "../../../middlewares"
import { AdminGetCollectionsParams } from "./list-collections" import { AdminGetCollectionsParams } from "./list-collections"
import { AdminPostCollectionsReq } from "./create-collection" import { AdminPostCollectionsReq } from "./create-collection"
import { AdminPostCollectionsCollectionReq } from "./update-collection" import { AdminPostCollectionsCollectionReq } from "./update-collection"
@@ -20,14 +23,11 @@ export default (app) => {
) )
route.get( route.get(
"/", "/",
transformQuery( transformQuery(AdminGetCollectionsParams, {
AdminGetCollectionsParams, defaultRelations: defaultAdminCollectionsRelations,
{ defaultFields: defaultAdminCollectionsFields,
defaultRelations: defaultAdminCollectionsRelations, isList: true,
defaultFields: defaultAdminCollectionsFields, }),
isList: true,
}
),
middlewares.wrap(require("./list-collections").default) middlewares.wrap(require("./list-collections").default)
) )
@@ -146,7 +146,7 @@ export default async (req: Request, res: Response) => {
const { const {
validatedQuery: { limit, offset }, validatedQuery: { limit, offset },
filterableFields, filterableFields,
listConfig listConfig,
} = req } = req
const [collections, count] = await productCollectionService.listAndCount( const [collections, count] = await productCollectionService.listAndCount(
@@ -174,6 +174,7 @@ export class AdminGetCollectionsPaginationParams {
offset = 0 offset = 0
} }
// eslint-disable-next-line max-len
export class AdminGetCollectionsParams extends AdminGetCollectionsPaginationParams { export class AdminGetCollectionsParams extends AdminGetCollectionsPaginationParams {
@IsOptional() @IsOptional()
@IsString() @IsString()
@@ -1,6 +1,6 @@
import { ArrayNotEmpty, IsString } from "class-validator" import { ArrayNotEmpty, IsString } from "class-validator"
import { Request, Response } from "express" import { Request, Response } from "express"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
import ProductCollectionService from "../../../../services/product-collection" import ProductCollectionService from "../../../../services/product-collection"
@@ -77,7 +77,9 @@ import ProductCollectionService from "../../../../services/product-collection"
*/ */
export default async (req: Request, res: Response) => { export default async (req: Request, res: Response) => {
const { id } = req.params const { id } = req.params
const { validatedBody } = req as { validatedBody: AdminDeleteProductsFromCollectionReq } const { validatedBody } = req as {
validatedBody: AdminDeleteProductsFromCollectionReq
}
const productCollectionService: ProductCollectionService = req.scope.resolve( const productCollectionService: ProductCollectionService = req.scope.resolve(
"productCollectionService" "productCollectionService"
@@ -85,7 +87,9 @@ export default async (req: Request, res: Response) => {
const manager: EntityManager = req.scope.resolve("manager") const manager: EntityManager = req.scope.resolve("manager")
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
return await productCollectionService.withTransaction(transactionManager).removeProducts(id, validatedBody.product_ids) return await productCollectionService
.withTransaction(transactionManager)
.removeProducts(id, validatedBody.product_ids)
}) })
res.json({ res.json({
@@ -1,6 +1,6 @@
import { IsObject, IsOptional, IsString } from "class-validator" import { IsObject, IsOptional, IsString } from "class-validator"
import { Request, Response } from "express" import { Request, Response } from "express"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
import ProductCollectionService from "../../../../services/product-collection" import ProductCollectionService from "../../../../services/product-collection"
/** /**
@@ -4,7 +4,7 @@ import TaxInclusivePricingFeatureFlag from "../../../../loaders/feature-flags/ta
import { PaginatedResponse } from "../../../../types/common" import { PaginatedResponse } from "../../../../types/common"
import middlewares, { import middlewares, {
transformBody, transformBody,
transformQuery transformQuery,
} from "../../../middlewares" } from "../../../middlewares"
import { isFeatureFlagEnabled } from "../../../middlewares/feature-flag-enabled" import { isFeatureFlagEnabled } from "../../../middlewares/feature-flag-enabled"
import { AdminGetCurrenciesParams } from "./list-currencies" import { AdminGetCurrenciesParams } from "./list-currencies"
@@ -12,10 +12,7 @@ import { AdminPostCurrenciesCurrencyReq } from "./update-currency"
export default (app) => { export default (app) => {
const route = Router() const route = Router()
app.use( app.use("/currencies", route)
"/currencies",
route
)
route.get( route.get(
"/", "/",
@@ -45,4 +42,3 @@ export type AdminCurrenciesRes = {
export * from "./list-currencies" export * from "./list-currencies"
export * from "./update-currency" export * from "./update-currency"
@@ -147,6 +147,7 @@ export default async (req, res) => {
res.status(200).json({ discount }) res.status(200).json({ discount })
} }
// eslint-disable-next-line max-len
export class AdminPostDiscountsDiscountConditions extends AdminUpsertConditionsReq { export class AdminPostDiscountsDiscountConditions extends AdminUpsertConditionsReq {
@IsString() @IsString()
operator: DiscountConditionOperator operator: DiscountConditionOperator
@@ -152,6 +152,7 @@ export default async (req, res) => {
res.status(200).json({ discount }) res.status(200).json({ discount })
} }
// eslint-disable-next-line max-len
export class AdminPostDiscountsDiscountConditionsCondition extends AdminUpsertConditionsReq {} export class AdminPostDiscountsDiscountConditionsCondition extends AdminUpsertConditionsReq {}
export class AdminPostDiscountsDiscountConditionsConditionParams { export class AdminPostDiscountsDiscountConditionsConditionParams {
@@ -213,6 +213,7 @@ export default async (req: Request, res) => {
}) })
} }
// eslint-disable-next-line max-len
export class AdminGetPriceListsPriceListProductsParams extends extendedFindParamsMixin( export class AdminGetPriceListsPriceListProductsParams extends extendedFindParamsMixin(
{ limit: 50 } { limit: 50 }
) { ) {
@@ -187,6 +187,7 @@ export default async (req: Request, res) => {
}) })
} }
// eslint-disable-next-line max-len
export class AdminGetPriceListPaginationParams extends FilterablePriceListProps { export class AdminGetPriceListPaginationParams extends FilterablePriceListProps {
@IsNumber() @IsNumber()
@IsOptional() @IsOptional()
@@ -201,6 +201,7 @@ export class AdminGetProductTagsPaginationParams {
offset = 0 offset = 0
} }
// eslint-disable-next-line max-len
export class AdminGetProductTagsParams extends AdminGetProductTagsPaginationParams { export class AdminGetProductTagsParams extends AdminGetProductTagsPaginationParams {
@IsType([String, [String], StringComparisonOperator]) @IsType([String, [String], StringComparisonOperator])
@IsOptional() @IsOptional()
@@ -202,6 +202,7 @@ export class AdminGetProductTypesPaginationParams {
offset? = 0 offset? = 0
} }
// eslint-disable-next-line max-len
export class AdminGetProductTypesParams extends AdminGetProductTypesPaginationParams { export class AdminGetProductTypesParams extends AdminGetProductTypesPaginationParams {
@IsType([String, [String], StringComparisonOperator]) @IsType([String, [String], StringComparisonOperator])
@IsOptional() @IsOptional()
@@ -90,7 +90,7 @@ export default async (req, res) => {
try { try {
const userService: UserService = req.scope.resolve("userService") const userService: UserService = req.scope.resolve("userService")
const decoded = (await jwt.decode(validated.token)) as payload const decoded = jwt.decode(validated.token) as payload
let user: User let user: User
try { try {
@@ -104,10 +104,10 @@ export default async (req, res) => {
throw new MedusaError(MedusaError.Types.INVALID_DATA, "invalid token") throw new MedusaError(MedusaError.Types.INVALID_DATA, "invalid token")
} }
const verifiedToken = (await jwt.verify( const verifiedToken = jwt.verify(
validated.token, validated.token,
user.password_hash user.password_hash
)) as payload ) as payload
if (!verifiedToken || verifiedToken.user_id !== user.id) { if (!verifiedToken || verifiedToken.user_id !== user.id) {
res.status(401).send("Invalid or expired password reset token") res.status(401).send("Invalid or expired password reset token")
return return
@@ -55,12 +55,7 @@ export default async (req, res) => {
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
idempotencyKey = await idempotencyKeyService idempotencyKey = await idempotencyKeyService
.withTransaction(transactionManager) .withTransaction(transactionManager)
.initializeRequest( .initializeRequest(headerKey, req.method, req.params, req.path)
headerKey,
req.method,
req.params,
req.path
)
}) })
} catch (error) { } catch (error) {
console.log(error) console.log(error)
@@ -85,21 +80,23 @@ export default async (req, res) => {
.workStage( .workStage(
idempotencyKey.idempotency_key, idempotencyKey.idempotency_key,
async (manager: EntityManager) => { async (manager: EntityManager) => {
const cart = await cartService.withTransaction(manager).retrieve( const cart = await cartService
id, .withTransaction(manager)
{ .retrieve(
relations: ["items", "items.adjustments"], id,
select: [ {
"total", relations: ["items", "items.adjustments"],
"subtotal", select: [
"tax_total", "total",
"discount_total", "subtotal",
"shipping_total", "tax_total",
"gift_card_total", "discount_total",
], "shipping_total",
}, "gift_card_total",
{ force_taxes: true } ],
) },
{ force_taxes: true }
)
const data = await decorateLineItemsWithTotals(cart, req, { const data = await decorateLineItemsWithTotals(cart, req, {
force_taxes: true, force_taxes: true,
@@ -131,14 +128,11 @@ export default async (req, res) => {
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
idempotencyKey = await idempotencyKeyService idempotencyKey = await idempotencyKeyService
.withTransaction(transactionManager) .withTransaction(transactionManager)
.update( .update(idempotencyKey.idempotency_key, {
idempotencyKey.idempotency_key, recovery_point: "finished",
{ response_code: 500,
recovery_point: "finished", response_body: { message: "Unknown recovery point" },
response_code: 500, })
response_body: { message: "Unknown recovery point" },
}
)
}) })
break break
} }
@@ -1,4 +1,4 @@
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
import { AbstractCartCompletionStrategy } from "../../../../interfaces" import { AbstractCartCompletionStrategy } from "../../../../interfaces"
import { IdempotencyKey } from "../../../../models/idempotency-key" import { IdempotencyKey } from "../../../../models/idempotency-key"
import { IdempotencyKeyService } from "../../../../services" import { IdempotencyKeyService } from "../../../../services"
@@ -88,12 +88,9 @@ export default async (req, res) => {
let idempotencyKey: IdempotencyKey let idempotencyKey: IdempotencyKey
try { try {
idempotencyKey = await manager.transaction(async (transactionManager) => { idempotencyKey = await manager.transaction(async (transactionManager) => {
return await idempotencyKeyService.withTransaction(transactionManager).initializeRequest( return await idempotencyKeyService
headerKey, .withTransaction(transactionManager)
req.method, .initializeRequest(headerKey, req.method, req.params, req.path)
req.params,
req.path
)
}) })
} catch (error) { } catch (error) {
console.log(error) console.log(error)
@@ -1,8 +1,8 @@
import { defaultStoreCartFields, defaultStoreCartRelations } from "." import { defaultStoreCartFields, defaultStoreCartRelations } from "."
import { CartService } from "../../../../services" import { CartService } from "../../../../services"
import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals" import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
import IdempotencyKeyService from "../../../../services/idempotency-key"; import IdempotencyKeyService from "../../../../services/idempotency-key"
/** /**
* @oas [post] /carts/{id}/payment-sessions * @oas [post] /carts/{id}/payment-sessions
@@ -61,12 +61,9 @@ export default async (req, res) => {
let idempotencyKey let idempotencyKey
try { try {
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
idempotencyKey = await idempotencyKeyService.withTransaction(transactionManager).initializeRequest( idempotencyKey = await idempotencyKeyService
headerKey, .withTransaction(transactionManager)
req.method, .initializeRequest(headerKey, req.method, req.params, req.path)
req.params,
req.path
)
}) })
} catch (error) { } catch (error) {
res.status(409).send("Failed to create idempotency key") res.status(409).send("Failed to create idempotency key")
@@ -89,23 +86,28 @@ export default async (req, res) => {
.workStage( .workStage(
idempotencyKey.idempotency_key, idempotencyKey.idempotency_key,
async (stageManager) => { async (stageManager) => {
await cartService.withTransaction(stageManager).setPaymentSessions(id) await cartService
.withTransaction(stageManager)
.setPaymentSessions(id)
const cart = await cartService.withTransaction(stageManager).retrieve(id, { const cart = await cartService
select: defaultStoreCartFields, .withTransaction(stageManager)
relations: defaultStoreCartRelations, .retrieve(id, {
}) select: defaultStoreCartFields,
relations: defaultStoreCartRelations,
})
const data = await decorateLineItemsWithTotals(cart, req, { const data = await decorateLineItemsWithTotals(cart, req, {
force_taxes: false, force_taxes: false,
transactionManager: stageManager transactionManager: stageManager,
}) })
return { return {
response_code: 200, response_code: 200,
response_body: { cart: data }, response_body: { cart: data },
} }
}) }
)
if (error) { if (error) {
inProgress = false inProgress = false
@@ -126,14 +128,11 @@ export default async (req, res) => {
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
idempotencyKey = await idempotencyKeyService idempotencyKey = await idempotencyKeyService
.withTransaction(transactionManager) .withTransaction(transactionManager)
.update( .update(idempotencyKey.idempotency_key, {
idempotencyKey.idempotency_key, recovery_point: "finished",
{ response_code: 500,
recovery_point: "finished", response_body: { message: "Unknown recovery point" },
response_code: 500, })
response_body: { message: "Unknown recovery point" },
}
)
}) })
break break
} }
@@ -1,12 +1,14 @@
import { Request } from "express" import { Request } from "express"
import { TotalsService } from "../../../../services" import { TotalsService } from "../../../../services"
import { Cart, LineItem } from "../../../../models" import { Cart, LineItem } from "../../../../models"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
export const decorateLineItemsWithTotals = async ( export const decorateLineItemsWithTotals = async (
cart: Cart, cart: Cart,
req: Request, req: Request,
options: { force_taxes: boolean, transactionManager?: EntityManager } = { force_taxes: false } options: { force_taxes: boolean; transactionManager?: EntityManager } = {
force_taxes: false,
}
): Promise<Cart> => { ): Promise<Cart> => {
const totalsService: TotalsService = req.scope.resolve("totalsService") const totalsService: TotalsService = req.scope.resolve("totalsService")
@@ -15,10 +17,13 @@ export const decorateLineItemsWithTotals = async (
const totalsServiceTx = totalsService.withTransaction(manager) const totalsServiceTx = totalsService.withTransaction(manager)
return await Promise.all( return await Promise.all(
cart.items.map(async (item: LineItem) => { cart.items.map(async (item: LineItem) => {
const itemTotals = await totalsServiceTx const itemTotals = await totalsServiceTx.getLineItemTotals(
.getLineItemTotals(item, cart, { item,
cart,
{
include_tax: options.force_taxes || cart.region.automatic_taxes, include_tax: options.force_taxes || cart.region.automatic_taxes,
}) }
)
return Object.assign(item, itemTotals) return Object.assign(item, itemTotals)
}) })
@@ -29,7 +34,8 @@ export const decorateLineItemsWithTotals = async (
if (options.transactionManager) { if (options.transactionManager) {
items = await getItems(options.transactionManager) items = await getItems(options.transactionManager)
} else { } else {
const manager: EntityManager = options.transactionManager ?? req.scope.resolve("manager") const manager: EntityManager =
options.transactionManager ?? req.scope.resolve("manager")
items = await manager.transaction(async (transactionManager) => { items = await manager.transaction(async (transactionManager) => {
return await getItems(transactionManager) return await getItems(transactionManager)
}) })
@@ -1,7 +1,7 @@
import { defaultStoreCartFields, defaultStoreCartRelations } from "." import { defaultStoreCartFields, defaultStoreCartRelations } from "."
import { CartService } from "../../../../services" import { CartService } from "../../../../services"
import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals" import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
/** /**
* @oas [delete] /carts/{id}/payment-sessions/{provider_id} * @oas [delete] /carts/{id}/payment-sessions/{provider_id}
@@ -54,7 +54,9 @@ export default async (req, res) => {
const manager: EntityManager = req.scope.resolve("manager") const manager: EntityManager = req.scope.resolve("manager")
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
return await cartService.withTransaction(transactionManager).deletePaymentSession(id, provider_id) return await cartService
.withTransaction(transactionManager)
.deletePaymentSession(id, provider_id)
}) })
const cart = await cartService.retrieve(id, { const cart = await cartService.retrieve(id, {
@@ -2,9 +2,12 @@ import { Router } from "express"
import "reflect-metadata" import "reflect-metadata"
import { Cart, Order, Swap } from "../../../../" import { Cart, Order, Swap } from "../../../../"
import { DeleteResponse, EmptyQueryParams } from "../../../../types/common" import { DeleteResponse, EmptyQueryParams } from "../../../../types/common"
import middlewares, { transformBody, transformQuery } from "../../../middlewares" import middlewares, {
import { StorePostCartsCartReq } from "./update-cart"; transformBody,
import { StorePostCartReq } from "./create-cart"; transformQuery,
} from "../../../middlewares"
import { StorePostCartsCartReq } from "./update-cart"
import { StorePostCartReq } from "./create-cart"
const route = Router() const route = Router()
export default (app, container) => { export default (app, container) => {
@@ -1,6 +1,6 @@
import { CartService } from "../../../../services" import { CartService } from "../../../../services"
import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals" import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
/** /**
* @oas [post] /carts/{id}/payment-sessions/{provider_id}/refresh * @oas [post] /carts/{id}/payment-sessions/{provider_id}/refresh
@@ -53,7 +53,9 @@ export default async (req, res) => {
const manager: EntityManager = req.scope.resolve("manager") const manager: EntityManager = req.scope.resolve("manager")
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
return await cartService.withTransaction(transactionManager).refreshPaymentSession(id, provider_id) return await cartService
.withTransaction(transactionManager)
.refreshPaymentSession(id, provider_id)
}) })
const cart = await cartService.retrieve(id, { const cart = await cartService.retrieve(id, {
select: [ select: [
@@ -1,7 +1,7 @@
import { defaultStoreCartFields, defaultStoreCartRelations } from "." import { defaultStoreCartFields, defaultStoreCartRelations } from "."
import { CartService } from "../../../../services" import { CartService } from "../../../../services"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
import { IsString } from "class-validator" import { IsString } from "class-validator"
import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals" import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals"
import { validator } from "../../../../utils/validator" import { validator } from "../../../../utils/validator"
@@ -68,7 +68,9 @@ export default async (req, res) => {
const manager: EntityManager = req.scope.resolve("manager") const manager: EntityManager = req.scope.resolve("manager")
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
return await cartService.withTransaction(transactionManager).setPaymentSession(id, validated.provider_id) return await cartService
.withTransaction(transactionManager)
.setPaymentSession(id, validated.provider_id)
}) })
const cart = await cartService.retrieve(id, { const cart = await cartService.retrieve(id, {
@@ -9,10 +9,10 @@ import { defaultStoreCartFields, defaultStoreCartRelations } from "."
import { AddressPayload } from "../../../../types/common" import { AddressPayload } from "../../../../types/common"
import { CartService } from "../../../../services" import { CartService } from "../../../../services"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
import { FeatureFlagDecorators } from "../../../../utils/feature-flag-decorators"; import { FeatureFlagDecorators } from "../../../../utils/feature-flag-decorators"
import { IsType } from "../../../../utils/validators/is-type" import { IsType } from "../../../../utils/validators/is-type"
import SalesChannelFeatureFlag from "../../../../loaders/feature-flags/sales-channels"; import SalesChannelFeatureFlag from "../../../../loaders/feature-flags/sales-channels"
import { Type } from "class-transformer" import { Type } from "class-transformer"
import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals" import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals"
@@ -139,12 +139,16 @@ export default async (req, res) => {
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
await cartService.withTransaction(transactionManager).update(id, validated) await cartService.withTransaction(transactionManager).update(id, validated)
const updated = await cartService.withTransaction(transactionManager).retrieve(id, { const updated = await cartService
relations: ["payment_sessions", "shipping_methods"], .withTransaction(transactionManager)
}) .retrieve(id, {
relations: ["payment_sessions", "shipping_methods"],
})
if (updated.payment_sessions?.length && !validated.region_id) { if (updated.payment_sessions?.length && !validated.region_id) {
await cartService.withTransaction(transactionManager).setPaymentSessions(id) await cartService
.withTransaction(transactionManager)
.setPaymentSessions(id)
} }
}) })
@@ -73,7 +73,9 @@ export default async (req, res) => {
if (validated.quantity === 0) { if (validated.quantity === 0) {
await cartService.withTransaction(m).removeLineItem(id, line_id) await cartService.withTransaction(m).removeLineItem(id, line_id)
} else { } else {
const cart = await cartService.withTransaction(m).retrieve(id, { relations: ["items"] }) const cart = await cartService
.withTransaction(m)
.retrieve(id, { relations: ["items"] })
const existing = cart.items.find((i) => i.id === line_id) const existing = cart.items.find((i) => i.id === line_id)
if (!existing) { if (!existing) {
@@ -3,7 +3,7 @@ import { defaultStoreCartFields, defaultStoreCartRelations } from "."
import { CartService } from "../../../../services" import { CartService } from "../../../../services"
import { validator } from "../../../../utils/validator" import { validator } from "../../../../utils/validator"
import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals" import { decorateLineItemsWithTotals } from "./decorate-line-items-with-totals"
import { EntityManager } from "typeorm"; import { EntityManager } from "typeorm"
/** /**
* @oas [post] /carts/{id}/payment-sessions/{provider_id} * @oas [post] /carts/{id}/payment-sessions/{provider_id}
@@ -70,8 +70,12 @@ export default async (req, res) => {
const manager: EntityManager = req.scope.resolve("manager") const manager: EntityManager = req.scope.resolve("manager")
await manager.transaction(async (transactionManager) => { await manager.transaction(async (transactionManager) => {
await cartService.withTransaction(transactionManager).setPaymentSession(id, provider_id) await cartService
await cartService.withTransaction(transactionManager).updatePaymentSession(id, validated.data) .withTransaction(transactionManager)
.setPaymentSession(id, provider_id)
await cartService
.withTransaction(transactionManager)
.updatePaymentSession(id, validated.data)
}) })
const cart = await cartService.retrieve(id, { const cart = await cartService.retrieve(id, {
@@ -238,6 +238,7 @@ export class StoreGetCustomersCustomerOrdersPaginationParams {
expand?: string expand?: string
} }
// eslint-disable-next-line max-len
export class StoreGetCustomersCustomerOrdersParams extends StoreGetCustomersCustomerOrdersPaginationParams { export class StoreGetCustomersCustomerOrdersParams extends StoreGetCustomersCustomerOrdersPaginationParams {
@IsString() @IsString()
@IsOptional() @IsOptional()
@@ -95,4 +95,5 @@ export default async (req, res) => {
res.json({ customer }) res.json({ customer })
} }
// eslint-disable-next-line max-len
export class StorePostCustomersCustomerAddressesAddressReq extends AddressPayload {} export class StorePostCustomersCustomerAddressesAddressReq extends AddressPayload {}
+2 -2
View File
@@ -5,7 +5,7 @@ import chokidar from "chokidar"
import Logger from "../loaders/logger" import Logger from "../loaders/logger"
export default async function({ port, directory }) { export default async function ({ port, directory }) {
const args = process.argv const args = process.argv
args.shift() args.shift()
args.shift() args.shift()
@@ -35,7 +35,7 @@ export default async function({ port, directory }) {
child.kill("SIGINT") child.kill("SIGINT")
execSync(`${babelPath} src -d dist --extensions \".ts,.js\"`, { execSync(`${babelPath} src -d dist --extensions ".ts,.js"`, {
cwd: directory, cwd: directory,
stdio: ["pipe", process.stdout, process.stderr], stdio: ["pipe", process.stdout, process.stderr],
}) })
+1 -1
View File
@@ -34,5 +34,5 @@ export default async function ({ port, directory }) {
return { dbConnection, server } return { dbConnection, server }
} }
let { dbConnection, server } = await start() const { dbConnection, server } = await start()
} }
+1 -1
View File
@@ -6,7 +6,7 @@ import { track } from "medusa-telemetry"
import loaders from "../loaders" import loaders from "../loaders"
export default async function({ directory, id, email, password, keepAlive }) { export default async function ({ directory, id, email, password, keepAlive }) {
track("CLI_USER", { with_id: !!id }) track("CLI_USER", { with_id: !!id })
const app = express() const app = express()
try { try {
+4 -2
View File
@@ -10,7 +10,7 @@ import passportLoader from "../loaders/passport"
import featureFlagLoader, { featureFlagRouter } from "../loaders/feature-flags" import featureFlagLoader, { featureFlagRouter } from "../loaders/feature-flags"
import servicesLoader from "../loaders/services" import servicesLoader from "../loaders/services"
import strategiesLoader from "../loaders/strategies" import strategiesLoader from "../loaders/strategies"
import logger from "../loaders/logger"; import logger from "../loaders/logger"
const adminSessionOpts = { const adminSessionOpts = {
cookieName: "session", cookieName: "session",
@@ -112,7 +112,9 @@ export async function request(method, url, opts = {}) {
} }
for (const name in headers) { for (const name in headers) {
req.set(name, headers[name]) if ({}.hasOwnProperty.call(headers, name)) {
req.set(name, headers[name])
}
} }
if (payload && !req.get("content-type")) { if (payload && !req.get("content-type")) {
@@ -61,10 +61,10 @@ export abstract class AbstractPaymentService<T extends TransactionBaseService>
protected static identifier: string protected static identifier: string
public getIdentifier(): string { public getIdentifier(): string {
if (!(<typeof AbstractPaymentService>this.constructor).identifier) { if (!(this.constructor as typeof AbstractPaymentService).identifier) {
throw new Error('Missing static property "identifier".') throw new Error(`Missing static property "identifier".`)
} }
return (<typeof AbstractPaymentService>this.constructor).identifier return (this.constructor as typeof AbstractPaymentService).identifier
} }
public abstract getPaymentData( public abstract getPaymentData(
@@ -102,7 +102,7 @@ export abstract class AbstractPaymentService<T extends TransactionBaseService>
public abstract deletePayment(paymentSession: PaymentSession): Promise<void> public abstract deletePayment(paymentSession: PaymentSession): Promise<void>
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
public retrieveSavedMethods(customer: Customer): Promise<Data[]> { public async retrieveSavedMethods(customer: Customer): Promise<Data[]> {
return Promise.resolve([]) return Promise.resolve([])
} }
@@ -67,10 +67,10 @@ export abstract class AbstractTaxService
protected static identifier: string protected static identifier: string
public getIdentifier(): string { public getIdentifier(): string {
if (!(<typeof AbstractTaxService>this.constructor).identifier) { if (!(this.constructor as typeof AbstractTaxService).identifier) {
throw new Error('Missing static property "identifier".') throw new Error(`Missing static property "identifier".`)
} }
return (<typeof AbstractTaxService>this.constructor).identifier return (this.constructor as typeof AbstractTaxService).identifier
} }
public abstract getTaxLines( public abstract getTaxLines(
@@ -15,7 +15,7 @@ export abstract class TransactionBaseService {
return this return this
} }
const cloned = new (<any>this.constructor)( const cloned = new (this.constructor as any)(
{ {
...this.__container__, ...this.__container__,
manager: transactionManager, manager: transactionManager,
@@ -111,14 +111,14 @@ export abstract class TransactionBaseService {
try { try {
result = await this.manager_.transaction( result = await this.manager_.transaction(
isolation as IsolationLevel, isolation as IsolationLevel,
(m) => doWork(m) async (m) => doWork(m)
) )
return result return result
} catch (error) { } catch (error) {
if (this.shouldRetryTransaction_(error)) { if (this.shouldRetryTransaction_(error)) {
return this.manager_.transaction( return this.manager_.transaction(
isolation as IsolationLevel, isolation as IsolationLevel,
(m): Promise<never | TResult> => doWork(m) async (m): Promise<never | TResult> => doWork(m)
) )
} else { } else {
if (errorHandler) { if (errorHandler) {
@@ -130,7 +130,7 @@ export abstract class TransactionBaseService {
} }
try { try {
return await this.manager_.transaction((m) => doWork(m)) return await this.manager_.transaction(async (m) => doWork(m))
} catch (error) { } catch (error) {
if (errorHandler) { if (errorHandler) {
const result = await errorHandler(error) const result = await errorHandler(error)
+1 -1
View File
@@ -1,4 +1,4 @@
import { Express } from 'express' import { Express } from "express"
import bodyParser from "body-parser" import bodyParser from "body-parser"
import routes from "../api" import routes from "../api"
import { AwilixContainer } from "awilix" import { AwilixContainer } from "awilix"
+4 -1
View File
@@ -9,7 +9,10 @@ type Options = {
container: AwilixContainer container: AwilixContainer
} }
export default async ({ container, configModule }: Options): Promise<Connection> => { export default async ({
container,
configModule,
}: Options): Promise<Connection> => {
const entities = container.resolve("db_entities") const entities = container.resolve("db_entities")
const isSqlite = configModule.projectConfig.database_type === "sqlite" const isSqlite = configModule.projectConfig.database_type === "sqlite"
+11 -9
View File
@@ -19,8 +19,8 @@ import {
TaxProviderService, TaxProviderService,
} from "../services" } from "../services"
import { CurrencyRepository } from "../repositories/currency" import { CurrencyRepository } from "../repositories/currency"
import { FlagRouter } from "../utils/flag-router"; import { FlagRouter } from "../utils/flag-router"
import SalesChannelFeatureFlag from "./feature-flags/sales-channels"; import SalesChannelFeatureFlag from "./feature-flags/sales-channels"
import { AbstractPaymentService, AbstractTaxService } from "../interfaces" import { AbstractPaymentService, AbstractTaxService } from "../interfaces"
const silentResolution = <T>( const silentResolution = <T>(
@@ -69,7 +69,9 @@ export default async ({
const profileService = container.resolve<ShippingProfileService>( const profileService = container.resolve<ShippingProfileService>(
"shippingProfileService" "shippingProfileService"
) )
const salesChannelService = container.resolve<SalesChannelService>("salesChannelService") const salesChannelService = container.resolve<SalesChannelService>(
"salesChannelService"
)
const logger = container.resolve<Logger>("logger") const logger = container.resolve<Logger>("logger")
const featureFlagRouter = container.resolve<FlagRouter>("featureFlagRouter") const featureFlagRouter = container.resolve<FlagRouter>("featureFlagRouter")
@@ -120,11 +122,9 @@ export default async ({
await storeService.withTransaction(manager).create() await storeService.withTransaction(manager).create()
const payProviders = const payProviders =
silentResolution<(typeof BasePaymentService | AbstractPaymentService<never>)[]>( silentResolution<
container, (typeof BasePaymentService | AbstractPaymentService<never>)[]
"paymentProviders", >(container, "paymentProviders", logger) || []
logger
) || []
const payIds = payProviders.map((p) => p.getIdentifier()) const payIds = payProviders.map((p) => p.getIdentifier())
const pProviderService = container.resolve<PaymentProviderService>( const pProviderService = container.resolve<PaymentProviderService>(
@@ -173,7 +173,9 @@ export default async ({
await profileService.withTransaction(manager).createDefault() await profileService.withTransaction(manager).createDefault()
await profileService.withTransaction(manager).createGiftCardDefault() await profileService.withTransaction(manager).createGiftCardDefault()
const isSalesChannelEnabled = featureFlagRouter.isFeatureEnabled(SalesChannelFeatureFlag.key) const isSalesChannelEnabled = featureFlagRouter.isFeatureEnabled(
SalesChannelFeatureFlag.key
)
if (isSalesChannelEnabled) { if (isSalesChannelEnabled) {
await salesChannelService.withTransaction(manager).createDefault() await salesChannelService.withTransaction(manager).createDefault()
} }
+4 -4
View File
@@ -1,4 +1,4 @@
import { Express } from 'express' import { Express } from "express"
import session from "express-session" import session from "express-session"
import cookieParser from "cookie-parser" import cookieParser from "cookie-parser"
import morgan from "morgan" import morgan from "morgan"
@@ -7,7 +7,7 @@ import createStore from "connect-redis"
import { ConfigModule } from "../types/global" import { ConfigModule } from "../types/global"
type Options = { type Options = {
app: Express; app: Express
configModule: ConfigModule configModule: ConfigModule
} }
@@ -23,7 +23,7 @@ export default async ({ app, configModule }: Options): Promise<Express> => {
} }
const { cookie_secret } = configModule.projectConfig const { cookie_secret } = configModule.projectConfig
let sessionOpts = { const sessionOpts = {
resave: true, resave: true,
saveUninitialized: true, saveUninitialized: true,
cookieName: "session", cookieName: "session",
@@ -34,7 +34,7 @@ export default async ({ app, configModule }: Options): Promise<Express> => {
secure, secure,
maxAge: 10 * 60 * 60 * 1000, maxAge: 10 * 60 * 60 * 1000,
}, },
store: null store: null,
} }
if (configModule?.projectConfig?.redis_url) { if (configModule?.projectConfig?.redis_url) {
@@ -30,7 +30,6 @@ export default (
const flagConfig: Record<string, boolean> = {} const flagConfig: Record<string, boolean> = {}
for (const flag of supportedFlags) { for (const flag of supportedFlags) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const flagSettings: FlagSettings = require(flag).default const flagSettings: FlagSettings = require(flag).default
if (!flagSettings) { if (!flagSettings) {
continue continue
+21 -13
View File
@@ -8,30 +8,38 @@ import { asClass, asValue, AwilixContainer } from "awilix"
/** /**
* Registers all models in the model directory * Registers all models in the model directory
*/ */
export default ({ container }: { container: MedusaContainer }, config = { register: true }) => { export default (
{ container }: { container: MedusaContainer },
config = { register: true }
) => {
const corePath = "../models/*.js" const corePath = "../models/*.js"
const coreFull = path.join(__dirname, corePath) const coreFull = path.join(__dirname, corePath)
const models: (ClassConstructor<unknown> | EntitySchema)[] = [] const models: (ClassConstructor<unknown> | EntitySchema)[] = []
const core = glob.sync(coreFull, { cwd: __dirname, ignore: ["index.js", "index.ts"] }) const core = glob.sync(coreFull, {
cwd: __dirname,
ignore: ["index.js", "index.ts"],
})
core.forEach((fn) => { core.forEach((fn) => {
const loaded = require(fn) as ClassConstructor<unknown> | EntitySchema const loaded = require(fn) as ClassConstructor<unknown> | EntitySchema
if (loaded) { if (loaded) {
Object.entries(loaded).map(([, val]: [string, ClassConstructor<unknown> | EntitySchema]) => { Object.entries(loaded).map(
if (typeof val === "function" || val instanceof EntitySchema) { ([, val]: [string, ClassConstructor<unknown> | EntitySchema]) => {
if (config.register) { if (typeof val === "function" || val instanceof EntitySchema) {
const name = formatRegistrationName(fn) if (config.register) {
container.register({ const name = formatRegistrationName(fn)
[name]: asClass(val as ClassConstructor<unknown>), container.register({
}) [name]: asClass(val as ClassConstructor<unknown>),
})
container.registerAdd("db_entities", asValue(val)) container.registerAdd("db_entities", asValue(val))
}
models.push(val)
} }
models.push(val)
} }
}) )
} }
}) })
+14 -3
View File
@@ -1,12 +1,20 @@
import passport from "passport" import passport from "passport"
import { AuthService } from "../services" import { AuthService } from "../services"
import { Express } from 'express' import { Express } from "express"
import { ConfigModule, MedusaContainer } from "../types/global" import { ConfigModule, MedusaContainer } from "../types/global"
import { Strategy as BearerStrategy } from "passport-http-bearer" import { Strategy as BearerStrategy } from "passport-http-bearer"
import { Strategy as JWTStrategy } from "passport-jwt" import { Strategy as JWTStrategy } from "passport-jwt"
import { Strategy as LocalStrategy } from "passport-local" import { Strategy as LocalStrategy } from "passport-local"
export default async ({ app, container, configModule }: { app: Express; container: MedusaContainer; configModule: ConfigModule; }): Promise<void> => { export default async ({
app,
container,
configModule,
}: {
app: Express
container: MedusaContainer
configModule: ConfigModule
}): Promise<void> => {
const authService = container.resolve<AuthService>("authService") const authService = container.resolve<AuthService>("authService")
// For good old email password authentication // For good old email password authentication
@@ -18,7 +26,10 @@ export default async ({ app, container, configModule }: { app: Express; containe
}, },
async (email, password, done) => { async (email, password, done) => {
try { try {
const { success, user } = await authService.authenticate(email, password) const { success, user } = await authService.authenticate(
email,
password
)
if (success) { if (success) {
return done(null, user) return done(null, user)
} else { } else {
+11 -9
View File
@@ -9,20 +9,22 @@ import { ClassConstructor, MedusaContainer } from "../types/global"
* Registers all models in the model directory * Registers all models in the model directory
*/ */
export default ({ container }: { container: MedusaContainer }): void => { export default ({ container }: { container: MedusaContainer }): void => {
let corePath = "../repositories/*.js" const corePath = "../repositories/*.js"
const coreFull = path.join(__dirname, corePath) const coreFull = path.join(__dirname, corePath)
const core = glob.sync(coreFull, { cwd: __dirname }) const core = glob.sync(coreFull, { cwd: __dirname })
core.forEach(fn => { core.forEach((fn) => {
const loaded = require(fn) as ClassConstructor<unknown> const loaded = require(fn) as ClassConstructor<unknown>
Object.entries(loaded).map(([, val]: [string, ClassConstructor<unknown>]) => { Object.entries(loaded).map(
if (typeof val === "function") { ([, val]: [string, ClassConstructor<unknown>]) => {
const name = formatRegistrationName(fn) if (typeof val === "function") {
container.register({ const name = formatRegistrationName(fn)
[name]: asClass(val), container.register({
}) [name]: asClass(val),
})
}
} }
}) )
}) })
} }
+4 -2
View File
@@ -5,10 +5,12 @@ import { AbstractSearchService } from "../interfaces"
export const SEARCH_INDEX_EVENT = "SEARCH_INDEX_EVENT" export const SEARCH_INDEX_EVENT = "SEARCH_INDEX_EVENT"
function loadProductsIntoSearchEngine(container: MedusaContainer): void { async function loadProductsIntoSearchEngine(
container: MedusaContainer
): Promise<void> {
const logger: Logger = container.resolve<Logger>("logger") const logger: Logger = container.resolve<Logger>("logger")
const eventBusService: EventBusService = container.resolve("eventBusService") const eventBusService: EventBusService = container.resolve("eventBusService")
eventBusService.emit(SEARCH_INDEX_EVENT, {}).catch((err) => { void eventBusService.emit(SEARCH_INDEX_EVENT, {}).catch((err) => {
logger.error(err) logger.error(err)
logger.error( logger.error(
"Something went wrong while emitting the search indexing event." "Something went wrong while emitting the search indexing event."
+3 -4
View File
@@ -6,17 +6,16 @@ import { ConfigModule, MedusaContainer } from "../types/global"
import { isDefined } from "../utils" import { isDefined } from "../utils"
type Options = { type Options = {
container: MedusaContainer; container: MedusaContainer
configModule: ConfigModule configModule: ConfigModule
isTest?: boolean; isTest?: boolean
} }
/** /**
* Registers all services in the services directory * Registers all services in the services directory
*/ */
export default ({ container, configModule, isTest }: Options): void => { export default ({ container, configModule, isTest }: Options): void => {
const useMock = const useMock = isDefined(isTest) ? isTest : process.env.NODE_ENV === "test"
isDefined(isTest) ? isTest : process.env.NODE_ENV === "test"
const corePath = useMock ? "../services/__mocks__/*.js" : "../services/*.js" const corePath = useMock ? "../services/__mocks__/*.js" : "../services/*.js"
const coreFull = path.join(__dirname, corePath) const coreFull = path.join(__dirname, corePath)
@@ -40,7 +40,6 @@ export default ({ container, configModule, isTest }: LoaderOptions): void => {
}) })
core.forEach((fn) => { core.forEach((fn) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const loaded = require(fn).default const loaded = require(fn).default
const name = formatRegistrationName(fn) const name = formatRegistrationName(fn)
+2 -2
View File
@@ -15,9 +15,9 @@ export default ({ container }: { container: MedusaContainer }) => {
const coreFull = path.join(__dirname, corePath) const coreFull = path.join(__dirname, corePath)
const core = glob.sync(coreFull, { cwd: __dirname }) const core = glob.sync(coreFull, { cwd: __dirname })
core.forEach(fn => { core.forEach((fn) => {
const loaded = require(fn).default const loaded = require(fn).default
container.build(asFunction(cradle => new loaded(cradle)).singleton()) container.build(asFunction((cradle) => new loaded(cradle)).singleton())
}) })
} }
+1 -1
View File
@@ -2,4 +2,4 @@ import { EntityRepository, Repository } from "typeorm"
import { Address } from "../models/address" import { Address } from "../models/address"
@EntityRepository(Address) @EntityRepository(Address)
export class AddressRepository extends Repository<Address> { } export class AddressRepository extends Repository<Address> {}
+1 -1
View File
@@ -22,7 +22,7 @@ export class CartRepository extends Repository<Cart> {
} }
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.entries(groupedRelations).map(([_, rels]) => { Object.entries(groupedRelations).map(async ([_, rels]) => {
return this.findByIds(entitiesIds, { return this.findByIds(entitiesIds, {
select: ["id"], select: ["id"],
relations: rels as string[], relations: rels as string[],
+1 -1
View File
@@ -1,4 +1,4 @@
import { EntityRepository, Repository } from "typeorm" import { EntityRepository, Repository } from "typeorm"
import { ClaimOrder } from "../models/claim-order" import { ClaimOrder } from "../models/claim-order"
@EntityRepository(ClaimOrder) @EntityRepository(ClaimOrder)
+1 -1
View File
@@ -2,4 +2,4 @@ import { EntityRepository, Repository } from "typeorm"
import { Country } from "../models/country" import { Country } from "../models/country"
@EntityRepository(Country) @EntityRepository(Country)
export class CountryRepository extends Repository<Country> { } export class CountryRepository extends Repository<Country> {}
+1 -1
View File
@@ -2,4 +2,4 @@ import { EntityRepository, Repository } from "typeorm"
import { Currency } from "../models" import { Currency } from "../models"
@EntityRepository(Currency) @EntityRepository(Currency)
export class CurrencyRepository extends Repository<Currency> { } export class CurrencyRepository extends Repository<Currency> {}
@@ -1,5 +1,6 @@
import { EntityRepository, Repository } from "typeorm" import { EntityRepository, Repository } from "typeorm"
import { CustomShippingOption } from './../models/custom-shipping-option'; import { CustomShippingOption } from "./../models/custom-shipping-option"
@EntityRepository(CustomShippingOption) @EntityRepository(CustomShippingOption)
// eslint-disable-next-line max-len
export class CustomShippingOptionRepository extends Repository<CustomShippingOption> {} export class CustomShippingOptionRepository extends Repository<CustomShippingOption> {}
@@ -4,13 +4,13 @@ import {
EntityTarget, EntityTarget,
In, In,
Not, Not,
Repository Repository,
} from "typeorm" } from "typeorm"
import { Discount } from "../models" import { Discount } from "../models"
import { import {
DiscountCondition, DiscountCondition,
DiscountConditionOperator, DiscountConditionOperator,
DiscountConditionType DiscountConditionType,
} from "../models/discount-condition" } from "../models/discount-condition"
import { DiscountConditionCustomerGroup } from "../models/discount-condition-customer-group" import { DiscountConditionCustomerGroup } from "../models/discount-condition-customer-group"
import { DiscountConditionProduct } from "../models/discount-condition-product" import { DiscountConditionProduct } from "../models/discount-condition-product"
@@ -282,7 +282,9 @@ export class DiscountConditionRepository extends Repository<DiscountCondition> {
.where("discon.discount_rule_id = :discountRuleId", { .where("discon.discount_rule_id = :discountRuleId", {
discountRuleId, discountRuleId,
}) })
.andWhere("discon.type = :type", { type: DiscountConditionType.CUSTOMER_GROUPS }) .andWhere("discon.type = :type", {
type: DiscountConditionType.CUSTOMER_GROUPS,
})
.getMany() .getMany()
// in case of no discount conditions, we assume that the discount // in case of no discount conditions, we assume that the discount
@@ -2,4 +2,4 @@ import { EntityRepository, Repository } from "typeorm"
import { DiscountRule } from "../models/discount-rule" import { DiscountRule } from "../models/discount-rule"
@EntityRepository(DiscountRule) @EntityRepository(DiscountRule)
export class DiscountRuleRepository extends Repository<DiscountRule> { } export class DiscountRuleRepository extends Repository<DiscountRule> {}
@@ -2,6 +2,5 @@ import { EntityRepository, Repository } from "typeorm"
import { FulfillmentProvider } from "../models/fulfillment-provider" import { FulfillmentProvider } from "../models/fulfillment-provider"
@EntityRepository(FulfillmentProvider) @EntityRepository(FulfillmentProvider)
export class FulfillmentProviderRepository extends Repository< // eslint-disable-next-line max-len
FulfillmentProvider export class FulfillmentProviderRepository extends Repository<FulfillmentProvider> {}
> {}
@@ -2,6 +2,5 @@ import { EntityRepository, Repository } from "typeorm"
import { GiftCardTransaction } from "../models/gift-card-transaction" import { GiftCardTransaction } from "../models/gift-card-transaction"
@EntityRepository(GiftCardTransaction) @EntityRepository(GiftCardTransaction)
export class GiftCardTransactionRepository extends Repository< // eslint-disable-next-line max-len
GiftCardTransaction export class GiftCardTransactionRepository extends Repository<GiftCardTransaction> {}
> {}
@@ -41,7 +41,7 @@ export class GiftCardRepository extends Repository<GiftCard> {
} }
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.entries(groupedRelations).map(([_, rels]) => { Object.entries(groupedRelations).map(async ([_, rels]) => {
return this.findByIds(entitiesIds, { return this.findByIds(entitiesIds, {
select: ["id"], select: ["id"],
relations: rels as string[], relations: rels as string[],
@@ -2,5 +2,5 @@ import { EntityRepository, Repository } from "typeorm"
import { LineItemAdjustment } from "../models/line-item-adjustment" import { LineItemAdjustment } from "../models/line-item-adjustment"
@EntityRepository(LineItemAdjustment) @EntityRepository(LineItemAdjustment)
// eslint-disable-next-line max-len
export class LineItemAdjustmentRepository extends Repository<LineItemAdjustment> {} export class LineItemAdjustmentRepository extends Repository<LineItemAdjustment> {}
@@ -2,6 +2,5 @@ import { EntityRepository, Repository } from "typeorm"
import { NotificationProvider } from "../models/notification-provider" import { NotificationProvider } from "../models/notification-provider"
@EntityRepository(NotificationProvider) @EntityRepository(NotificationProvider)
export class NotificationProviderRepository extends Repository< // eslint-disable-next-line max-len
NotificationProvider export class NotificationProviderRepository extends Repository<NotificationProvider> {}
> {}
+1 -1
View File
@@ -22,7 +22,7 @@ export class OrderRepository extends Repository<Order> {
} }
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.entries(groupedRelations).map(([_, rels]) => { Object.entries(groupedRelations).map(async ([_, rels]) => {
return this.findByIds(entitiesIds, { return this.findByIds(entitiesIds, {
select: ["id"], select: ["id"],
relations: rels as string[], relations: rels as string[],
+1 -1
View File
@@ -2,4 +2,4 @@ import { EntityRepository, Repository } from "typeorm"
import { Payment } from "../models/payment" import { Payment } from "../models/payment"
@EntityRepository(Payment) @EntityRepository(Payment)
export class PaymentRepository extends Repository<Payment> { } export class PaymentRepository extends Repository<Payment> {}
@@ -76,7 +76,7 @@ export class PriceListRepository extends Repository<PriceList> {
} }
const entitiesIds = entities.map(({ id }) => id) const entitiesIds = entities.map(({ id }) => id)
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.values(groupedRelations).map((relations: string[]) => { Object.values(groupedRelations).map(async (relations: string[]) => {
return this.findByIds(entitiesIds, { return this.findByIds(entitiesIds, {
select: ["id"], select: ["id"],
relations: relations as string[], relations: relations as string[],
@@ -2,6 +2,5 @@ import { EntityRepository, Repository } from "typeorm"
import { ProductCollection } from "../models/product-collection" import { ProductCollection } from "../models/product-collection"
@EntityRepository(ProductCollection) @EntityRepository(ProductCollection)
export class ProductCollectionRepository extends Repository< // eslint-disable-next-line max-len
ProductCollection export class ProductCollectionRepository extends Repository<ProductCollection> {}
> {}
@@ -2,4 +2,5 @@ import { EntityRepository, Repository } from "typeorm"
import { ProductOptionValue } from "../models/product-option-value" import { ProductOptionValue } from "../models/product-option-value"
@EntityRepository(ProductOptionValue) @EntityRepository(ProductOptionValue)
export class ProductOptionValueRepository extends Repository<ProductOptionValue> { } // eslint-disable-next-line max-len
export class ProductOptionValueRepository extends Repository<ProductOptionValue> {}
@@ -2,4 +2,4 @@ import { EntityRepository, Repository } from "typeorm"
import { ProductOption } from "../models/product-option" import { ProductOption } from "../models/product-option"
@EntityRepository(ProductOption) @EntityRepository(ProductOption)
export class ProductOptionRepository extends Repository<ProductOption> { } export class ProductOptionRepository extends Repository<ProductOption> {}
@@ -81,8 +81,8 @@ export class ProductVariantRepository extends Repository<ProductVariant> {
withDeleted = false withDeleted = false
): Promise<ProductVariant[]> { ): Promise<ProductVariant[]> {
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.entries(groupedRelations).map(([toplevel, rels]) => { Object.entries(groupedRelations).map(async ([toplevel, rels]) => {
let querybuilder = this.createQueryBuilder("pv").leftJoinAndSelect( const querybuilder = this.createQueryBuilder("pv").leftJoinAndSelect(
`pv.${toplevel}`, `pv.${toplevel}`,
toplevel toplevel
) )
+2 -5
View File
@@ -6,10 +6,7 @@ import {
In, In,
Repository, Repository,
} from "typeorm" } from "typeorm"
import { PriceList, import { PriceList, Product, SalesChannel } from "../models"
Product,
SalesChannel
} from "../models"
import { import {
ExtendedFindConfig, ExtendedFindConfig,
Selector, Selector,
@@ -143,7 +140,7 @@ export class ProductRepository extends Repository<Product> {
select: (keyof Product)[] = [] select: (keyof Product)[] = []
): Promise<Product[]> { ): Promise<Product[]> {
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.entries(groupedRelations).map(([toplevel, rels]) => { Object.entries(groupedRelations).map(async ([toplevel, rels]) => {
let querybuilder = this.createQueryBuilder("products") let querybuilder = this.createQueryBuilder("products")
if (select && select.length) { if (select && select.length) {
@@ -43,7 +43,7 @@ export class SalesChannelRepository extends Repository<SalesChannel> {
} }
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.entries(groupedRelations).map(([_, rels]) => { Object.entries(groupedRelations).map(async ([_, rels]) => {
return this.findByIds(entitiesIds, { return this.findByIds(entitiesIds, {
select: ["id"], select: ["id"],
relations: rels as string[], relations: rels as string[],
@@ -3,6 +3,7 @@ import { ShippingMethodTaxLine } from "../models/shipping-method-tax-line"
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity" import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity"
@EntityRepository(ShippingMethodTaxLine) @EntityRepository(ShippingMethodTaxLine)
// eslint-disable-next-line max-len
export class ShippingMethodTaxLineRepository extends Repository<ShippingMethodTaxLine> { export class ShippingMethodTaxLineRepository extends Repository<ShippingMethodTaxLine> {
async upsertLines( async upsertLines(
lines: ShippingMethodTaxLine[] lines: ShippingMethodTaxLine[]
@@ -2,4 +2,5 @@ import { EntityRepository, Repository } from "typeorm"
import { ShippingOptionRequirement } from "../models/shipping-option-requirement" import { ShippingOptionRequirement } from "../models/shipping-option-requirement"
@EntityRepository(ShippingOptionRequirement) @EntityRepository(ShippingOptionRequirement)
// eslint-disable-next-line max-len
export class ShippingOptionRequirementRepository extends Repository<ShippingOptionRequirement> {} export class ShippingOptionRequirementRepository extends Repository<ShippingOptionRequirement> {}
+1 -1
View File
@@ -22,7 +22,7 @@ export class SwapRepository extends Repository<Swap> {
} }
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await Promise.all(
Object.entries(groupedRelations).map(([_, rels]) => { Object.entries(groupedRelations).map(async ([_, rels]) => {
return this.findByIds(entitiesIds, { return this.findByIds(entitiesIds, {
select: ["id"], select: ["id"],
relations: rels as string[], relations: rels as string[],
+8 -8
View File
@@ -27,12 +27,12 @@ const resolveableFields = [
@EntityRepository(TaxRate) @EntityRepository(TaxRate)
export class TaxRateRepository extends Repository<TaxRate> { export class TaxRateRepository extends Repository<TaxRate> {
getFindQueryBuilder(findOptions: FindManyOptions<TaxRate>) { getFindQueryBuilder(findOptions: FindManyOptions<TaxRate>) {
let qb = this.createQueryBuilder("tr") const qb = this.createQueryBuilder("tr")
const cleanOptions = findOptions const cleanOptions = findOptions
const resolverFields: string[] = [] const resolverFields: string[] = []
if (isDefined(findOptions.select)) { if (isDefined(findOptions.select)) {
let selectableCols: (keyof TaxRate)[] = [] const selectableCols: (keyof TaxRate)[] = []
for (const k of findOptions.select) { for (const k of findOptions.select) {
if (!resolveableFields.includes(k)) { if (!resolveableFields.includes(k)) {
selectableCols.push(k) selectableCols.push(k)
@@ -116,7 +116,7 @@ export class TaxRateRepository extends Repository<TaxRate> {
async addToProduct( async addToProduct(
id: string, id: string,
productIds: string[], productIds: string[],
overrideExisting: boolean = false overrideExisting = false
): Promise<ProductTaxRate[]> { ): Promise<ProductTaxRate[]> {
const toInsert = productIds.map((pId) => ({ rate_id: id, product_id: pId })) const toInsert = productIds.map((pId) => ({ rate_id: id, product_id: pId }))
const insertResult = await this.createQueryBuilder() const insertResult = await this.createQueryBuilder()
@@ -155,7 +155,7 @@ export class TaxRateRepository extends Repository<TaxRate> {
async addToProductType( async addToProductType(
id: string, id: string,
productTypeIds: string[], productTypeIds: string[],
overrideExisting: boolean = false overrideExisting = false
): Promise<ProductTypeTaxRate[]> { ): Promise<ProductTypeTaxRate[]> {
const toInsert = productTypeIds.map((pId) => ({ const toInsert = productTypeIds.map((pId) => ({
rate_id: id, rate_id: id,
@@ -197,7 +197,7 @@ export class TaxRateRepository extends Repository<TaxRate> {
async addToShippingOption( async addToShippingOption(
id: string, id: string,
optionIds: string[], optionIds: string[],
overrideExisting: boolean = false overrideExisting = false
): Promise<ShippingTaxRate[]> { ): Promise<ShippingTaxRate[]> {
const toInsert = optionIds.map((pId) => ({ const toInsert = optionIds.map((pId) => ({
rate_id: id, rate_id: id,
@@ -226,12 +226,12 @@ export class TaxRateRepository extends Repository<TaxRate> {
} }
async listByProduct(productId: string, config: TaxRateListByConfig) { async listByProduct(productId: string, config: TaxRateListByConfig) {
let productRates = this.createQueryBuilder("txr") const productRates = this.createQueryBuilder("txr")
.leftJoin(ProductTaxRate, "ptr", "ptr.rate_id = txr.id") .leftJoin(ProductTaxRate, "ptr", "ptr.rate_id = txr.id")
.leftJoin(Product, "prod", "prod.id = ptr.product_id") .leftJoin(Product, "prod", "prod.id = ptr.product_id")
.where("prod.id = :productId", { productId }) .where("prod.id = :productId", { productId })
let typeRates = this.createQueryBuilder("txr") const typeRates = this.createQueryBuilder("txr")
.leftJoin(ProductTypeTaxRate, "pttr", "pttr.rate_id = txr.id") .leftJoin(ProductTypeTaxRate, "pttr", "pttr.rate_id = txr.id")
.leftJoin(Product, "prod", "prod.type_id = pttr.product_type_id") .leftJoin(Product, "prod", "prod.type_id = pttr.product_type_id")
.where("prod.id = :productId", { productId }) .where("prod.id = :productId", { productId })
@@ -256,7 +256,7 @@ export class TaxRateRepository extends Repository<TaxRate> {
} }
async listByShippingOption(optionId: string) { async listByShippingOption(optionId: string) {
let rates = this.createQueryBuilder("txr") const rates = this.createQueryBuilder("txr")
.leftJoin(ShippingTaxRate, "ptr", "ptr.rate_id = txr.id") .leftJoin(ShippingTaxRate, "ptr", "ptr.rate_id = txr.id")
.where("ptr.shipping_option_id = :optionId", { optionId }) .where("ptr.shipping_option_id = :optionId", { optionId })
@@ -5,7 +5,7 @@ import { EventBusServiceMock } from "../__mocks__/event-bus"
describe("NoteService", () => { describe("NoteService", () => {
describe("list", () => { describe("list", () => {
const noteRepo = MockRepository({ const noteRepo = MockRepository({
find: q => { find: (q) => {
return Promise.resolve([ return Promise.resolve([
{ id: IdMap.getId("note"), value: "some note" }, { id: IdMap.getId("note"), value: "some note" },
]) ])
@@ -40,7 +40,7 @@ describe("NoteService", () => {
describe("retrieve", () => { describe("retrieve", () => {
const noteRepo = MockRepository({ const noteRepo = MockRepository({
findOne: q => { findOne: (q) => {
switch (q.where.id) { switch (q.where.id) {
case IdMap.getId("note"): case IdMap.getId("note"):
return Promise.resolve({ return Promise.resolve({
@@ -88,8 +88,8 @@ describe("NoteService", () => {
} }
const noteRepo = MockRepository({ const noteRepo = MockRepository({
create: f => Promise.resolve(note), create: (f) => note,
save: f => Promise.resolve(note), save: (f) => Promise.resolve(note),
}) })
const noteService = new NoteService({ const noteService = new NoteService({
@@ -137,8 +137,8 @@ describe("NoteService", () => {
const note = { id: IdMap.getId("note") } const note = { id: IdMap.getId("note") }
const noteRepo = MockRepository({ const noteRepo = MockRepository({
findOne: f => Promise.resolve(note), findOne: (f) => Promise.resolve(note),
save: f => Promise.resolve(note), save: (f) => Promise.resolve(note),
}) })
const noteService = new NoteService({ const noteService = new NoteService({
@@ -172,8 +172,8 @@ describe("NoteService", () => {
const note = { id: IdMap.getId("note") } const note = { id: IdMap.getId("note") }
const noteRepo = MockRepository({ const noteRepo = MockRepository({
softRemove: f => Promise.resolve(), softRemove: (f) => Promise.resolve(),
findOne: f => Promise.resolve(note), findOne: (f) => Promise.resolve(note),
}) })
const noteService = new NoteService({ const noteService = new NoteService({
@@ -1,10 +1,10 @@
import { IdMap, MockRepository, MockManager } from "medusa-test-utils" import { IdMap, MockRepository, MockManager } from "medusa-test-utils"
import ProductService from "../product" import ProductService from "../product"
import { FlagRouter } from "../../utils/flag-router"; import { FlagRouter } from "../../utils/flag-router"
const eventBusService = { const eventBusService = {
emit: jest.fn(), emit: jest.fn(),
withTransaction: function() { withTransaction: function () {
return this return this
}, },
} }
@@ -110,7 +110,7 @@ describe("ProductService", () => {
productTypeRepository.upsertType = mockUpsertType productTypeRepository.upsertType = mockUpsertType
const productCollectionService = { const productCollectionService = {
withTransaction: function() { withTransaction: function () {
return this return this
}, },
retrieve: (id) => retrieve: (id) =>
@@ -250,7 +250,7 @@ describe("ProductService", () => {
const productVariantRepository = MockRepository() const productVariantRepository = MockRepository()
const productVariantService = { const productVariantService = {
withTransaction: function() { withTransaction: function () {
return this return this
}, },
update: (variant, update) => { update: (variant, update) => {
@@ -491,15 +491,14 @@ describe("ProductService", () => {
}) })
const productVariantService = { const productVariantService = {
withTransaction: function() { withTransaction: function () {
return this return this
}, },
addOptionValue: jest.fn(), addOptionValue: jest.fn(),
} }
const productOptionRepository = MockRepository({ const productOptionRepository = MockRepository({
create: () => create: () => ({ id: IdMap.getId("Material"), title: "Material" }),
Promise.resolve({ id: IdMap.getId("Material"), title: "Material" }),
}) })
const productService = new ProductService({ const productService = new ProductService({
+1 -2
View File
@@ -2092,8 +2092,7 @@ class CartService extends TransactionBaseService {
} }
const updatedCart = await cartRepo.save(cart) const updatedCart = await cartRepo.save(cart)
await this.eventBus_
this.eventBus_
.withTransaction(transactionManager) .withTransaction(transactionManager)
.emit(CartService.Events.UPDATED, updatedCart) .emit(CartService.Events.UPDATED, updatedCart)
+1 -1
View File
@@ -345,7 +345,7 @@ export default class ClaimService extends TransactionBaseService {
} }
newItems = await Promise.all( newItems = await Promise.all(
additional_items.map((i) => additional_items.map(async (i) =>
lineItemServiceTx.generate( lineItemServiceTx.generate(
i.variant_id, i.variant_id,
order.region_id, order.region_id,
+5 -5
View File
@@ -150,13 +150,13 @@ class CsvParser<
return columnMap[tupleKey] return columnMap[tupleKey]
} }
const matchedColumn = this.$$schema.columns.find((column) => const matchedColumn = this.$$schema.columns.find((column) => {
"match" in column && return "match" in column &&
typeof column.match === "object" && typeof column.match === "object" &&
column.match instanceof RegExp column.match instanceof RegExp
? column.match.test(tupleKey) ? column.match.test(tupleKey)
: false : false
) })
return matchedColumn return matchedColumn
} }
@@ -14,6 +14,7 @@ type InjectedDependencies = {
class CustomShippingOptionService extends TransactionBaseService { class CustomShippingOptionService extends TransactionBaseService {
protected manager_: EntityManager protected manager_: EntityManager
protected transactionManager_: EntityManager | undefined protected transactionManager_: EntityManager | undefined
// eslint-disable-next-line max-len
protected customShippingOptionRepository_: typeof CustomShippingOptionRepository protected customShippingOptionRepository_: typeof CustomShippingOptionRepository
constructor({ constructor({
@@ -9,8 +9,7 @@ import {
CustomerGroupUpdate, CustomerGroupUpdate,
FilterableCustomerGroupProps, FilterableCustomerGroupProps,
} from "../types/customer-groups" } from "../types/customer-groups"
import { isDefined } from "../utils" import { isDefined, formatException, PostgresError } from "../utils"
import { formatException } from "../utils/exception-formatter"
type CustomerGroupConstructorProps = { type CustomerGroupConstructorProps = {
manager: EntityManager manager: EntityManager
@@ -97,7 +96,7 @@ class CustomerGroupService extends BaseService {
return result return result
} catch (err) { } catch (err) {
if (err.code === "23505") { if (err.code === PostgresError.DUPLICATE_ERROR) {
throw new MedusaError(MedusaError.Types.DUPLICATE_ERROR, err.detail) throw new MedusaError(MedusaError.Types.DUPLICATE_ERROR, err.detail)
} }
throw err throw err
@@ -130,7 +129,7 @@ class CustomerGroupService extends BaseService {
return await cgRepo.addCustomers(id, ids) return await cgRepo.addCustomers(id, ids)
}, },
async (error) => { async (error) => {
if (error.code === "23503") { if (error.code === PostgresError.FOREIGN_KEY_ERROR) {
await this.retrieve(id) await this.retrieve(id)
const existingCustomers = await this.customerService_.list({ const existingCustomers = await this.customerService_.list({
+2 -2
View File
@@ -86,7 +86,7 @@ class CustomerService extends TransactionBaseService {
const payload = { customer_id: customer.id, exp: expiry } const payload = { customer_id: customer.id, exp: expiry }
const token = jwt.sign(payload, secret) const token = jwt.sign(payload, secret)
// Notify subscribers // Notify subscribers
this.eventBusService_ void this.eventBusService_
.withTransaction(manager) .withTransaction(manager)
.emit(CustomerService.Events.PASSWORD_RESET, { .emit(CustomerService.Events.PASSWORD_RESET, {
id: customerId, id: customerId,
@@ -488,7 +488,7 @@ class CustomerService extends TransactionBaseService {
) )
if (shouldAdd) { if (shouldAdd) {
const created = await addressRepository.create({ const created = addressRepository.create({
...address, ...address,
customer_id: customerId, customer_id: customerId,
}) })
@@ -13,9 +13,8 @@ import {
import { DiscountConditionRepository } from "../repositories/discount-condition" import { DiscountConditionRepository } from "../repositories/discount-condition"
import { FindConfig } from "../types/common" import { FindConfig } from "../types/common"
import { UpsertDiscountConditionInput } from "../types/discount" import { UpsertDiscountConditionInput } from "../types/discount"
import { PostgresError } from "../utils/exception-formatter"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { buildQuery } from "../utils" import { buildQuery, PostgresError } from "../utils"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -28,6 +27,7 @@ type InjectedDependencies = {
* @implements {BaseService} * @implements {BaseService}
*/ */
class DiscountConditionService extends TransactionBaseService { class DiscountConditionService extends TransactionBaseService {
// eslint-disable-next-line max-len
protected readonly discountConditionRepository_: typeof DiscountConditionRepository protected readonly discountConditionRepository_: typeof DiscountConditionRepository
protected readonly eventBus_: EventBusService protected readonly eventBus_: EventBusService
+10 -7
View File
@@ -6,13 +6,13 @@ import {
DeepPartial, DeepPartial,
EntityManager, EntityManager,
ILike, ILike,
SelectQueryBuilder SelectQueryBuilder,
} from "typeorm" } from "typeorm"
import { import {
EventBusService, EventBusService,
ProductService, ProductService,
RegionService, RegionService,
TotalsService TotalsService,
} from "." } from "."
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import TaxInclusivePricingFeatureFlag from "../loaders/feature-flags/tax-inclusive-pricing" import TaxInclusivePricingFeatureFlag from "../loaders/feature-flags/tax-inclusive-pricing"
@@ -20,7 +20,7 @@ import { Cart, Discount, LineItem, Region } from "../models"
import { import {
AllocationType as DiscountAllocation, AllocationType as DiscountAllocation,
DiscountRule, DiscountRule,
DiscountRuleType DiscountRuleType,
} from "../models/discount-rule" } from "../models/discount-rule"
import { DiscountRepository } from "../repositories/discount" import { DiscountRepository } from "../repositories/discount"
import { DiscountConditionRepository } from "../repositories/discount-condition" import { DiscountConditionRepository } from "../repositories/discount-condition"
@@ -33,7 +33,7 @@ import {
CreateDynamicDiscountInput, CreateDynamicDiscountInput,
FilterableDiscountProps, FilterableDiscountProps,
UpdateDiscountInput, UpdateDiscountInput,
UpdateDiscountRuleInput UpdateDiscountRuleInput,
} from "../types/discount" } from "../types/discount"
import { buildQuery, setMetadata } from "../utils" import { buildQuery, setMetadata } from "../utils"
import { isFuture, isPast } from "../utils/date-helpers" import { isFuture, isPast } from "../utils/date-helpers"
@@ -54,6 +54,7 @@ class DiscountService extends TransactionBaseService {
protected readonly customerService_: CustomerService protected readonly customerService_: CustomerService
protected readonly discountRuleRepository_: typeof DiscountRuleRepository protected readonly discountRuleRepository_: typeof DiscountRuleRepository
protected readonly giftCardRepository_: typeof GiftCardRepository protected readonly giftCardRepository_: typeof GiftCardRepository
// eslint-disable-next-line max-len
protected readonly discountConditionRepository_: typeof DiscountConditionRepository protected readonly discountConditionRepository_: typeof DiscountConditionRepository
protected readonly discountConditionService_: DiscountConditionService protected readonly discountConditionService_: DiscountConditionService
protected readonly totalsService_: TotalsService protected readonly totalsService_: TotalsService
@@ -202,7 +203,7 @@ class DiscountService extends TransactionBaseService {
try { try {
if (discount.regions) { if (discount.regions) {
discount.regions = (await Promise.all( discount.regions = (await Promise.all(
discount.regions.map((regionId) => discount.regions.map(async (regionId) =>
this.regionService_.withTransaction(manager).retrieve(regionId) this.regionService_.withTransaction(manager).retrieve(regionId)
) )
)) as Region[] )) as Region[]
@@ -355,12 +356,14 @@ class DiscountService extends TransactionBaseService {
if (regions) { if (regions) {
discount.regions = await Promise.all( discount.regions = await Promise.all(
regions.map((regionId) => this.regionService_.retrieve(regionId)) regions.map(async (regionId) =>
this.regionService_.retrieve(regionId)
)
) )
} }
if (metadata) { if (metadata) {
discount.metadata = await setMetadata(discount, metadata) discount.metadata = setMetadata(discount, metadata)
} }
if (rule) { if (rule) {
+2 -2
View File
@@ -261,7 +261,7 @@ export default class EventBusService {
) )
return await Promise.all( return await Promise.all(
observers.map((subscriber) => { observers.map(async (subscriber) => {
return subscriber(data, eventName).catch((err) => { return subscriber(data, eventName).catch((err) => {
this.logger_.warn( this.logger_.warn(
`An error occurred while processing ${eventName}: ${err}` `An error occurred while processing ${eventName}: ${err}`
@@ -286,7 +286,7 @@ export default class EventBusService {
this.logger_.info(`Processing cron job: ${eventName}`) this.logger_.info(`Processing cron job: ${eventName}`)
return await Promise.all( return await Promise.all(
observers.map((subscriber) => { observers.map(async (subscriber) => {
return subscriber(data, eventName).catch((err) => { return subscriber(data, eventName).catch((err) => {
this.logger_.warn( this.logger_.warn(
`An error occured while processing ${eventName}: ${err}` `An error occured while processing ${eventName}: ${err}`
+9 -5
View File
@@ -9,19 +9,21 @@ import {
} from "../interfaces" } from "../interfaces"
class DefaultFileService extends AbstractFileService { class DefaultFileService extends AbstractFileService {
upload(fileData: Express.Multer.File): Promise<FileServiceUploadResult> { async upload(
fileData: Express.Multer.File
): Promise<FileServiceUploadResult> {
throw new MedusaError( throw new MedusaError(
MedusaError.Types.UNEXPECTED_STATE, MedusaError.Types.UNEXPECTED_STATE,
"Please add a file service plugin in order to manipulate files in Medusa" "Please add a file service plugin in order to manipulate files in Medusa"
) )
} }
delete(fileData: Record<string, any>): Promise<void> { async delete(fileData: Record<string, any>): Promise<void> {
throw new MedusaError( throw new MedusaError(
MedusaError.Types.UNEXPECTED_STATE, MedusaError.Types.UNEXPECTED_STATE,
"Please add a file service plugin in order to manipulate files in Medusa" "Please add a file service plugin in order to manipulate files in Medusa"
) )
} }
getUploadStreamDescriptor( async getUploadStreamDescriptor(
fileData: UploadStreamDescriptorType fileData: UploadStreamDescriptorType
): Promise<FileServiceGetUploadStreamResult> { ): Promise<FileServiceGetUploadStreamResult> {
throw new MedusaError( throw new MedusaError(
@@ -29,7 +31,7 @@ class DefaultFileService extends AbstractFileService {
"Please add a file service plugin in order to manipulate files in Medusa" "Please add a file service plugin in order to manipulate files in Medusa"
) )
} }
getDownloadStream( async getDownloadStream(
fileData: GetUploadedFileType fileData: GetUploadedFileType
): Promise<NodeJS.ReadableStream> { ): Promise<NodeJS.ReadableStream> {
throw new MedusaError( throw new MedusaError(
@@ -37,7 +39,9 @@ class DefaultFileService extends AbstractFileService {
"Please add a file service plugin in order to manipulate files in Medusa" "Please add a file service plugin in order to manipulate files in Medusa"
) )
} }
getPresignedDownloadUrl(fileData: GetUploadedFileType): Promise<string> { async getPresignedDownloadUrl(
fileData: GetUploadedFileType
): Promise<string> {
throw new MedusaError( throw new MedusaError(
MedusaError.Types.UNEXPECTED_STATE, MedusaError.Types.UNEXPECTED_STATE,
"Please add a file service plugin in order to manipulate files in Medusa" "Please add a file service plugin in order to manipulate files in Medusa"
@@ -1,5 +1,5 @@
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import BaseFulfillmentService from "medusa-interfaces/dist/fulfillment-service" import BaseFulfillmentService from "medusa-interfaces"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { import {
@@ -26,7 +26,7 @@ type FulfillmentProviderContainer = MedusaContainer & {
fulfillmentProviderRepository: typeof FulfillmentProviderRepository fulfillmentProviderRepository: typeof FulfillmentProviderRepository
manager: EntityManager manager: EntityManager
} & { } & {
[key in `${FulfillmentProviderKey}`]: BaseFulfillmentService [key in `${FulfillmentProviderKey}`]: typeof BaseFulfillmentService
} }
/** /**
@@ -37,7 +37,7 @@ class FulfillmentProviderService extends TransactionBaseService {
protected transactionManager_: EntityManager | undefined protected transactionManager_: EntityManager | undefined
protected readonly container_: FulfillmentProviderContainer protected readonly container_: FulfillmentProviderContainer
// eslint-disable-next-line max-len
protected readonly fulfillmentProviderRepository_: typeof FulfillmentProviderRepository protected readonly fulfillmentProviderRepository_: typeof FulfillmentProviderRepository
constructor(container: FulfillmentProviderContainer) { constructor(container: FulfillmentProviderContainer) {
@@ -77,14 +77,13 @@ class FulfillmentProviderService extends TransactionBaseService {
): Promise<FulfillmentOptions[]> { ): Promise<FulfillmentOptions[]> {
return await Promise.all( return await Promise.all(
providerIds.map(async (p) => { providerIds.map(async (p) => {
const provider = await this.retrieveProvider(p) const provider = this.retrieveProvider(p)
return { return {
provider_id: p, provider_id: p,
options: options: (await provider.getFulfillmentOptions()) as Record<
(await provider.getFulfillmentOptions()) as unknown as Record< string,
string, unknown
unknown >[],
>[],
} }
}) })
) )
@@ -94,7 +93,7 @@ class FulfillmentProviderService extends TransactionBaseService {
* @param providerId - the provider id * @param providerId - the provider id
* @return the payment fulfillment provider * @return the payment fulfillment provider
*/ */
retrieveProvider(providerId: string): BaseFulfillmentService { retrieveProvider(providerId: string): typeof BaseFulfillmentService {
try { try {
return this.container_[`fp_${providerId}`] return this.container_[`fp_${providerId}`]
} catch (err) { } catch (err) {
@@ -32,6 +32,7 @@ type InjectedDependencies = {
*/ */
class GiftCardService extends TransactionBaseService { class GiftCardService extends TransactionBaseService {
protected readonly giftCardRepository_: typeof GiftCardRepository protected readonly giftCardRepository_: typeof GiftCardRepository
// eslint-disable-next-line max-len
protected readonly giftCardTransactionRepo_: typeof GiftCardTransactionRepository protected readonly giftCardTransactionRepo_: typeof GiftCardTransactionRepository
protected readonly regionService_: RegionService protected readonly regionService_: RegionService
protected readonly eventBus_: EventBusService protected readonly eventBus_: EventBusService
+1 -1
View File
@@ -144,7 +144,7 @@ class InviteService extends BaseService {
invite = await inviteRepository.save(invite) invite = await inviteRepository.save(invite)
} else if (!invite) { } else if (!invite) {
// if no invite is found, create a new one // if no invite is found, create a new one
const created = await inviteRepository.create({ const created = inviteRepository.create({
role, role,
token: "", token: "",
user_email: user, user_email: user,
@@ -73,9 +73,8 @@ class LineItemAdjustmentService extends BaseService {
id: string, id: string,
config: FindConfig<LineItemAdjustment> = {} config: FindConfig<LineItemAdjustment> = {}
): Promise<LineItemAdjustment> { ): Promise<LineItemAdjustment> {
const lineItemAdjustmentRepo: LineItemAdjustmentRepository = this.manager_.getCustomRepository( const lineItemAdjustmentRepo: LineItemAdjustmentRepository =
this.lineItemAdjustmentRepo_ this.manager_.getCustomRepository(this.lineItemAdjustmentRepo_)
)
const query = this.buildQuery_({ id }, config) const query = this.buildQuery_({ id }, config)
const lineItemAdjustment = await lineItemAdjustmentRepo.findOne(query) const lineItemAdjustment = await lineItemAdjustmentRepo.findOne(query)
@@ -97,9 +96,8 @@ class LineItemAdjustmentService extends BaseService {
*/ */
async create(data: Partial<LineItemAdjustment>): Promise<LineItemAdjustment> { async create(data: Partial<LineItemAdjustment>): Promise<LineItemAdjustment> {
return await this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const lineItemAdjustmentRepo: LineItemAdjustmentRepository = manager.getCustomRepository( const lineItemAdjustmentRepo: LineItemAdjustmentRepository =
this.lineItemAdjustmentRepo_ manager.getCustomRepository(this.lineItemAdjustmentRepo_)
)
const lineItemAdjustment = lineItemAdjustmentRepo.create(data) const lineItemAdjustment = lineItemAdjustmentRepo.create(data)
@@ -118,9 +116,8 @@ class LineItemAdjustmentService extends BaseService {
data: Partial<LineItemAdjustment> data: Partial<LineItemAdjustment>
): Promise<LineItemAdjustment> { ): Promise<LineItemAdjustment> {
return await this.atomicPhase_(async (manager: EntityManager) => { return await this.atomicPhase_(async (manager: EntityManager) => {
const lineItemAdjustmentRepo: LineItemAdjustmentRepository = manager.getCustomRepository( const lineItemAdjustmentRepo: LineItemAdjustmentRepository =
this.lineItemAdjustmentRepo_ manager.getCustomRepository(this.lineItemAdjustmentRepo_)
)
const lineItemAdjustment = await this.retrieve(id) const lineItemAdjustment = await this.retrieve(id)
@@ -169,9 +166,8 @@ class LineItemAdjustmentService extends BaseService {
selectorOrId: string | FilterableLineItemAdjustmentProps selectorOrId: string | FilterableLineItemAdjustmentProps
): Promise<void> { ): Promise<void> {
return this.atomicPhase_(async (manager) => { return this.atomicPhase_(async (manager) => {
const lineItemAdjustmentRepo: LineItemAdjustmentRepository = manager.getCustomRepository( const lineItemAdjustmentRepo: LineItemAdjustmentRepository =
this.lineItemAdjustmentRepo_ manager.getCustomRepository(this.lineItemAdjustmentRepo_)
)
if (typeof selectorOrId === "string") { if (typeof selectorOrId === "string") {
return await this.delete({ id: selectorOrId }) return await this.delete({ id: selectorOrId })
@@ -302,7 +298,7 @@ class LineItemAdjustmentService extends BaseService {
} }
return await Promise.all( return await Promise.all(
cart.items.map((li) => this.createAdjustmentForLineItem(cart, li)) cart.items.map(async (li) => this.createAdjustmentForLineItem(cart, li))
) )
} }
} }
+1 -1
View File
@@ -112,7 +112,7 @@ class NoteService extends TransactionBaseService {
metadata, metadata,
} }
const note = await noteRepo.create(toCreate) const note = noteRepo.create(toCreate)
const result = await noteRepo.save(note) const result = await noteRepo.save(note)
await this.eventBus_ await this.eventBus_
+2 -1
View File
@@ -30,6 +30,7 @@ class NotificationService extends TransactionBaseService {
} }
protected readonly logger_: Logger protected readonly logger_: Logger
protected readonly notificationRepository_: typeof NotificationRepository protected readonly notificationRepository_: typeof NotificationRepository
// eslint-disable-next-line max-len
protected readonly notificationProviderRepository_: typeof NotificationProviderRepository protected readonly notificationProviderRepository_: typeof NotificationProviderRepository
constructor(container: InjectedDependencies) { constructor(container: InjectedDependencies) {
@@ -170,7 +171,7 @@ class NotificationService extends TransactionBaseService {
* @param data - the data the event was sent with * @param data - the data the event was sent with
* @return the result of notification subscribed * @return the result of notification subscribed
*/ */
handleEvent( async handleEvent(
eventName: string, eventName: string,
data: Record<string, unknown> data: Record<string, unknown>
): Promise<void | undefined | Notification[]> { ): Promise<void | undefined | Notification[]> {
+6 -6
View File
@@ -777,7 +777,7 @@ class OrderService extends TransactionBaseService {
await addrRepo.save({ ...addr, ...address }) await addrRepo.save({ ...addr, ...address })
} else { } else {
const created = await addrRepo.create({ ...address }) const created = addrRepo.create({ ...address })
await addrRepo.save(created) await addrRepo.save(created)
} }
} }
@@ -1071,8 +1071,8 @@ class OrderService extends TransactionBaseService {
if (p.captured_at === null) { if (p.captured_at === null) {
const result = await paymentProviderServiceTx const result = await paymentProviderServiceTx
.capturePayment(p) .capturePayment(p)
.catch((err) => { .catch(async (err) => {
this.eventBus_ await this.eventBus_
.withTransaction(manager) .withTransaction(manager)
.emit(OrderService.Events.PAYMENT_CAPTURE_FAILED, { .emit(OrderService.Events.PAYMENT_CAPTURE_FAILED, {
id: orderId, id: orderId,
@@ -1100,7 +1100,7 @@ class OrderService extends TransactionBaseService {
const result = await orderRepo.save(order) const result = await orderRepo.save(order)
if (order.payment_status === PaymentStatus.CAPTURED) { if (order.payment_status === PaymentStatus.CAPTURED) {
this.eventBus_ await this.eventBus_
.withTransaction(manager) .withTransaction(manager)
.emit(OrderService.Events.PAYMENT_CAPTURED, { .emit(OrderService.Events.PAYMENT_CAPTURED, {
id: result.id, id: result.id,
@@ -1412,7 +1412,7 @@ class OrderService extends TransactionBaseService {
const evaluatedNoNotification = const evaluatedNoNotification =
no_notification !== undefined ? no_notification : order.no_notification no_notification !== undefined ? no_notification : order.no_notification
this.eventBus_.emit(OrderService.Events.REFUND_CREATED, { await this.eventBus_.emit(OrderService.Events.REFUND_CREATED, {
id: result.id, id: result.id,
refund_id: refund.id, refund_id: refund.id,
no_notification: evaluatedNoNotification, no_notification: evaluatedNoNotification,
@@ -1574,7 +1574,7 @@ class OrderService extends TransactionBaseService {
if (refundAmount > order.refundable_amount) { if (refundAmount > order.refundable_amount) {
order.fulfillment_status = FulfillmentStatus.REQUIRES_ACTION order.fulfillment_status = FulfillmentStatus.REQUIRES_ACTION
const result = await orderRepo.save(order) const result = await orderRepo.save(order)
this.eventBus_ await this.eventBus_
.withTransaction(manager) .withTransaction(manager)
.emit(OrderService.Events.RETURN_ACTION_REQUIRED, { .emit(OrderService.Events.RETURN_ACTION_REQUIRED, {
id: result.id, id: result.id,
@@ -38,6 +38,7 @@ export default class PaymentProviderService extends TransactionBaseService {
protected transactionManager_: EntityManager | undefined protected transactionManager_: EntityManager | undefined
protected readonly container_: InjectedDependencies protected readonly container_: InjectedDependencies
protected readonly paymentSessionRepository_: typeof PaymentSessionRepository protected readonly paymentSessionRepository_: typeof PaymentSessionRepository
// eslint-disable-next-line max-len
protected readonly paymentProviderRepository_: typeof PaymentProviderRepository protected readonly paymentProviderRepository_: typeof PaymentProviderRepository
protected readonly paymentRepository_: typeof PaymentRepository protected readonly paymentRepository_: typeof PaymentRepository
protected readonly refundRepository_: typeof RefundRepository protected readonly refundRepository_: typeof RefundRepository
@@ -28,7 +28,7 @@ class ProductCollectionService extends TransactionBaseService {
protected transactionManager_: EntityManager | undefined protected transactionManager_: EntityManager | undefined
protected readonly eventBus_: EventBusService protected readonly eventBus_: EventBusService
// eslint-disable-next-line max-len
protected readonly productCollectionRepository_: typeof ProductCollectionRepository protected readonly productCollectionRepository_: typeof ProductCollectionRepository
protected readonly productRepository_: typeof ProductRepository protected readonly productRepository_: typeof ProductRepository
@@ -119,7 +119,7 @@ class ProductCollectionService extends TransactionBaseService {
) )
try { try {
const productCollection = await collectionRepo.create(collection) const productCollection = collectionRepo.create(collection)
return await collectionRepo.save(productCollection) return await collectionRepo.save(productCollection)
} catch (error) { } catch (error) {
throw formatException(error) throw formatException(error)
+1 -1
View File
@@ -649,7 +649,7 @@ class ProductService extends TransactionBaseService {
) )
} }
const option = await productOptionRepo.create({ const option = productOptionRepo.create({
title: optionTitle, title: optionTitle,
product_id: productId, product_id: productId,
}) })
+3 -1
View File
@@ -59,7 +59,9 @@ class RegionService extends TransactionBaseService {
protected readonly regionRepository_: typeof RegionRepository protected readonly regionRepository_: typeof RegionRepository
protected readonly countryRepository_: typeof CountryRepository protected readonly countryRepository_: typeof CountryRepository
protected readonly currencyRepository_: typeof CurrencyRepository protected readonly currencyRepository_: typeof CurrencyRepository
// eslint-disable-next-line max-len
protected readonly paymentProviderRepository_: typeof PaymentProviderRepository protected readonly paymentProviderRepository_: typeof PaymentProviderRepository
// eslint-disable-next-line max-len
protected readonly fulfillmentProviderRepository_: typeof FulfillmentProviderRepository protected readonly fulfillmentProviderRepository_: typeof FulfillmentProviderRepository
protected readonly taxProviderRepository_: typeof TaxProviderRepository protected readonly taxProviderRepository_: typeof TaxProviderRepository
@@ -281,7 +283,7 @@ class RegionService extends TransactionBaseService {
if (regionData.countries) { if (regionData.countries) {
region.countries = await Promise.all( region.countries = await Promise.all(
regionData.countries!.map((countryCode) => regionData.countries!.map(async (countryCode) =>
this.validateCountry(countryCode, id!) this.validateCountry(countryCode, id!)
) )
).catch((err) => { ).catch((err) => {
+2 -2
View File
@@ -151,7 +151,7 @@ class ReturnService extends TransactionBaseService {
* @param config - the config object for find * @param config - the config object for find
* @return the result of the find operation * @return the result of the find operation
*/ */
list( async list(
selector: Selector<Return>, selector: Selector<Return>,
config: FindConfig<Return> = { config: FindConfig<Return> = {
skip: 0, skip: 0,
@@ -453,7 +453,7 @@ class ReturnService extends TransactionBaseService {
}) })
) )
const created = (await returnRepository.create(returnObject)) as Return const created = returnRepository.create(returnObject)
const result = await returnRepository.save(created) const result = await returnRepository.save(created)
if (method && method.option_id) { if (method && method.option_id) {
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more