Adds discount decoration

This commit is contained in:
olivermrbl
2020-08-28 11:36:35 +02:00
parent eb47896668
commit 014354a16d
2 changed files with 42 additions and 1 deletions

View File

@@ -4,7 +4,22 @@ export default async (req, res) => {
const discountService = req.scope.resolve("discountService")
const data = await discountService.retrieve(discount_id)
res.status(200).json({ discount: data })
const discount = await discountService.decorate(
data,
[
"code",
"is_dynamic",
"discount_rule",
"usage_count",
"disabled",
"starts_at",
"ends_at",
"regions",
],
["valid_for"]
)
res.status(200).json({ discount })
} catch (err) {
throw err
}

View File

@@ -13,6 +13,7 @@ class DiscountService extends BaseService {
dynamicDiscountCodeModel,
totalsService,
productVariantService,
productService,
regionService,
eventBusService,
}) {
@@ -30,6 +31,9 @@ class DiscountService extends BaseService {
/** @private @const {ProductVariantService} */
this.productVariantService_ = productVariantService
/** @private @const {ProductService} */
this.productService_ = productService
/** @private @const {RegionService} */
this.regionService_ = regionService
@@ -431,6 +435,28 @@ class DiscountService extends BaseService {
throw new MedusaError(MedusaError.Types.DB_ERROR, err.message)
})
}
/**
* Decorates a discount.
* @param {Discount} discount - the discount to decorate.
* @param {string[]} fields - the fields to include.
* @param {string[]} expandFields - fields to expand.
* @return {Discount} return the decorated discount.
*/
async decorate(discount, fields = [], expandFields = []) {
const requiredFields = ["_id", "metadata"]
const decorated = _.pick(discount, fields.concat(requiredFields))
if (expandFields.includes("valid_for")) {
decorated.discount_rule.valid_for = await Promise.all(
decorated.discount_rule.valid_for.map(async p => {
return this.productService_.retrieve(p)
})
)
}
return decorated
}
}
export default DiscountService