Skip to main content
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.

Note

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:

src/strategies/price.ts
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:

src/strategies/price.ts
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.

dataobject[]Required
Holds the data necessary to perform the price selection for each variant ID.
contextPriceSelectionContextRequired
The context of the price selection

Returns

PromisePromise<Map<string, PriceSelectionResult>>Required
A map, each key is an ID of a variant, and its value is an object holding the price selection result.

3. Run Build Command

In your terminal, run the build command to transpile the files in the src directory into the dist directory:

npm run build

Test it Out

Run your backend to test it out:

npx medusa develop

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.

Was this section helpful?