Skip to main content

How to Override Price Selection Strategy

In this document, you’ll learn how to override Medusa’s price selection strategy to create a custom pricing strategy.

If you’re interested in learning what a price selection strategy is and how it works, check out this documentation instead.

1. Create Class

Create a TypeScript or JavaScript file in src/strategiesCopy to Clipboard of your Medusa backend project with a class that extends the AbstractPriceSelectionStrategyCopy to Clipboard class:

src/strategies/price.ts
import { 
AbstractPriceSelectionStrategy,
IPriceSelectionStrategy,
PriceSelectionContext,
PriceSelectionResult,
} from "@medusajs/medusa"

import { EntityManager } from "typeorm"

export default class MyStrategy extends
AbstractPriceSelectionStrategy {
withTransaction(
manager: EntityManager
): IPriceSelectionStrategy {
if (!manager) {
return this
}

return new MyStrategy()
}

async calculateVariantPrice(
variant_id: string,
context: PriceSelectionContext
): Promise<PriceSelectionResult> {
// TODO
}
}
Report Incorrect CodeCopy to Clipboard

You can use services or repositories in the strategy by adding them to the constructor and updating the parameters passed to the MyStrategyCopy to Clipboard constructor in withTransactionCopy to Clipboard. For example:

import { 
AbstractPriceSelectionStrategy,
CustomerService,
IPriceSelectionStrategy,
PriceSelectionContext,
PriceSelectionResult,
} from "@medusajs/medusa"

export default class MyStrategy extends
AbstractPriceSelectionStrategy {
private customerService: CustomerService

constructor({
customerService,
}) {
super()
this.customerService = customerService
}

withTransaction(
manager: EntityManager
): IPriceSelectionStrategy {
if (!manager) {
return this
}

return new MyStrategy({
customerService: this.customerService,
})
}
// ...
}
Report Incorrect CodeCopy to Clipboard

2. Implement calculateVariantPrice

Implement the price selection strategy you want inside the calculateVariantPriceCopy to Clipboard method.

This method accepts the variant ID as a first parameter and the context object as a second parameter.

This method must return an object having the following fields:

{
originalPrice, // number | null
calculatedPrice, // number | null
prices // MoneyAmount[]
}
Copy to Clipboard

You can learn more about optional properties and the meaning behind every property here.


3. Run Build Command

In your terminal, run the build command to transpile the files in the srcCopy to Clipboard directory into the distCopy to Clipboard directory:

yarn build
Report Incorrect CodeCopy to Clipboard

Test it Out

Run your backend to test it out:

npx @medusajs/medusa-cli develop
Report Incorrect CodeCopy to Clipboard

Then, try out your strategy using any of the Products or Carts endpoints which include retrieving product variants and line items respectively. You should then see the prices in the response based on your implemented strategy.

Was this page helpful?