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/strategies
of your Medusa backend project with a class that extends the AbstractPriceSelectionStrategy
class:
import {
AbstractPriceSelectionStrategy,
PriceSelectionContext,
PriceSelectionResult,
} from "@medusajs/medusa"
import {
TaxServiceRate,
} from "@medusajs/medusa/dist/types/tax-service"
export default class MyStrategy extends
AbstractPriceSelectionStrategy {
async calculateVariantPrice(
data: {
variantId: string;
taxRates: TaxServiceRate[];
quantity?: number
}[],
context: PriceSelectionContext
): Promise<Map<string, PriceSelectionResult>> {
throw new Error("Method not implemented.")
}
}
Resolve Resources
You can resolve resources like services or repositories using dependency injection.
For example:
import {
AbstractPriceSelectionStrategy,
CustomerService,
PriceSelectionContext,
PriceSelectionResult,
} from "@medusajs/medusa"
import {
TaxServiceRate,
} from "@medusajs/medusa/dist/types/tax-service"
type InjectedDependencies = {
customerService: CustomerService
}
export default class MyStrategy extends
AbstractPriceSelectionStrategy {
protected customerService_: CustomerService
constructor(container: InjectedDependencies) {
super(container)
this.customerService_ = container.customerService
}
// ...
}
2. Implement calculateVariantPrice
In this method, you can implement your price selection strategy.
Parameters
You can learn more about optional properties and the meaning behind every property here.
data
object[]RequiredHolds the data necessary to perform the price selection for each variant ID.
data
object[]RequiredThe context of the price selection
Returns
Promise
Promise<Map<string, PriceSelectionResult>>RequiredA map, each key is an ID of a variant, and its value is an object holding the price selection result.
Promise
Promise<Map<string, PriceSelectionResult>>Required3. Run Build Command
In your terminal, run the build command to transpile the files in the src
directory into the dist
directory:
Test it Out
Run your backend to test it out:
Then, try out your strategy using any of the Products or Carts API Routes which include retrieving product variants and line items respectively. You should then see the prices in the response based on your implemented strategy.