feat(pricing, types, utils, medusa-sdk): Pricing Module Setup + Currency (#4860)

What:

- Setups the skeleton for pricing module
- Creates service/model/repository for currency model
- Setups types
- Setups DB
- Moved some utils to a common place

RESOLVES CORE-1477
RESOLVES CORE-1476
This commit is contained in:
Riqwan Thamir authored and GitHub committed 2023-08-29 21:58:34 +00:00
1 parent 470379e631
commit 460161a69f
70 files changed
+3022 -75

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
/dist
node_modules
.DS_store
.env*
.env
*.sql
View File
Whitespace-only changes.
+3
View File
@@ -0,0 +1,3 @@
# Pricing Module
The Pricing Module gives you access MoneyAmounts, Currency and PriceList through a standalone package that can be installed and run in Next.js functions and other Node.js compatible runtimes.
@@ -0,0 +1,20 @@
export const defaultCurrencyData = [
{
symbol: "$",
name: "US Dollar",
symbol_native: "$",
code: "USD",
},
{
symbol: "CA$",
name: "Canadian Dollar",
symbol_native: "$",
code: "CAD",
},
{
symbol: "€",
name: "Euro",
symbol_native: "€",
code: "EUR",
},
]
@@ -0,0 +1,20 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency } from "@models"
import { defaultCurrencyData } from "./data"
export async function createCurrencies(
manager: SqlEntityManager,
currencyData: any[] = defaultCurrencyData
): Promise<Currency[]> {
const currencies: Currency[] = []
for (let curr of currencyData) {
const currency = manager.create(Currency, curr)
currencies.push(currency)
}
await manager.persistAndFlush(currencies)
return currencies
}
@@ -0,0 +1,277 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency } from "@models"
import { CurrencyRepository } from "@repositories"
import { CurrencyService } from "@services"
import { createCurrencies } from "../../../__fixtures__/currency"
import { MikroOrmWrapper } from "../../../utils"
jest.setTimeout(30000)
describe("Currency Service", () => {
let service: CurrencyService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: Currency[]
const currencyData = [
{
symbol: "$",
name: "US Dollar",
symbol_native: "$",
code: "USD",
},
{
symbol: "CA$",
name: "Canadian Dollar",
symbol_native: "$",
code: "CAD",
},
]
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
const currencyRepository = new CurrencyRepository({
manager: repositoryManager,
})
service = new CurrencyService({
currencyRepository,
})
testManager = await MikroOrmWrapper.forkManager()
data = await createCurrencies(testManager, currencyData)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("list", () => {
it("list currencies", async () => {
const currenciesResult = await service.list()
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
])
})
it("list currencies by code", async () => {
const currenciesResult = await service.list({ code: ["USD"] })
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
})
describe("listAndCount", () => {
it("should return currencies and count", async () => {
const [currenciesResult, count] = await service.listAndCount()
expect(count).toEqual(2)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
])
})
it("should return currencies and count when filtered", async () => {
const [currenciesResult, count] = await service.listAndCount({
code: ["USD"],
})
expect(count).toEqual(1)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("should return currencies and count when using skip and take", async () => {
const [currenciesResult, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(2)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
])
})
it("should return requested fields", async () => {
const [currenciesResult, count] = await service.listAndCount(
{},
{
take: 1,
select: ["code"],
}
)
const serialized = JSON.parse(JSON.stringify(currenciesResult))
expect(count).toEqual(2)
expect(serialized).toEqual([
{
code: "USD",
},
])
})
})
describe("retrieve", () => {
const code = "USD"
const name = "US Dollar"
it("should return currency for the given code", async () => {
const currency = await service.retrieve(code)
expect(currency).toEqual(
expect.objectContaining({
code,
})
)
})
it("should throw an error when currency with code does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"Currency with code: does-not-exist was not found"
)
})
it("should throw an error when a code is not provided", async () => {
let error
try {
await service.retrieve(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual('"currencyCode" must be defined')
})
it("should return currency based on config select param", async () => {
const currency = await service.retrieve(code, {
select: ["code", "name"],
})
const serialized = JSON.parse(JSON.stringify(currency))
expect(serialized).toEqual({
code,
name,
})
})
})
describe("delete", () => {
const code = "USD"
it("should delete the currencies given an code successfully", async () => {
await service.delete([code])
const currencies = await service.list({
code: [code],
})
expect(currencies).toHaveLength(0)
})
})
describe("update", () => {
const code = "USD"
it("should update the name of the currency successfully", async () => {
await service.update([
{
code,
name: "United States Pounds",
},
])
const currency = await service.retrieve(code)
expect(currency.name).toEqual("United States Pounds")
})
it("should throw an error when a code does not exist", async () => {
let error
try {
await service.update([
{
code: "does-not-exist",
name: "UK",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'Currency with code "does-not-exist" not found'
)
})
})
describe("create", () => {
it("should create a currency successfully", async () => {
await service.create([
{
code: "TES",
name: "Test Dollars",
symbol: "TES1",
symbol_native: "TES2",
},
])
const [currency] = await service.list({
code: ["TES"],
})
expect(currency).toEqual(
expect.objectContaining({
code: "TES",
name: "Test Dollars",
symbol: "TES1",
symbol_native: "TES2",
})
)
})
})
})
@@ -0,0 +1,269 @@
import { initialize } from "../../../../src"
import { IPricingModuleService } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency } from "@models"
import { createCurrencies } from "../../../__fixtures__/currency"
import { DB_URL, MikroOrmWrapper } from "../../../utils"
describe("PricingModuleService currency", () => {
let service: IPricingModuleService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
let data!: Currency[]
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = MikroOrmWrapper.forkManager()
service = await initialize({
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_PRICING_DB_SCHEMA,
},
})
testManager = MikroOrmWrapper.forkManager()
data = await createCurrencies(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("listCurrencies", () => {
it("list currencies", async () => {
const currenciesResult = await service.listCurrencies()
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
expect.objectContaining({
code: "EUR",
name: "Euro",
}),
])
})
it("list currencies by code", async () => {
const currenciesResult = await service.listCurrencies({ code: ["USD"] })
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
})
describe("listAndCountCurrencies", () => {
it("should return currencies and count", async () => {
const [currenciesResult, count] = await service.listAndCountCurrencies()
expect(count).toEqual(3)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
expect.objectContaining({
code: "EUR",
name: "Euro",
}),
])
})
it("should return currencies and count when filtered", async () => {
const [currenciesResult, count] = await service.listAndCountCurrencies({
code: ["USD"],
})
expect(count).toEqual(1)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "USD",
name: "US Dollar",
}),
])
})
it("should return currencies and count when using skip and take", async () => {
const [currenciesResult, count] = await service.listAndCountCurrencies(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(3)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "CAD",
name: "Canadian Dollar",
}),
])
})
it("should return requested fields", async () => {
const [currenciesResult, count] = await service.listAndCountCurrencies(
{},
{
take: 1,
select: ["code"],
}
)
const serialized = JSON.parse(JSON.stringify(currenciesResult))
expect(count).toEqual(3)
expect(serialized).toEqual([
{
code: "USD",
},
])
})
})
describe("retrieveCurrency", () => {
const code = "USD"
const name = "US Dollar"
it("should return currency for the given code", async () => {
const currency = await service.retrieveCurrency(code)
expect(currency).toEqual(
expect.objectContaining({
code,
})
)
})
it("should throw an error when currency with code does not exist", async () => {
let error
try {
await service.retrieveCurrency("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"Currency with code: does-not-exist was not found"
)
})
it("should throw an error when a code is not provided", async () => {
let error
try {
await service.retrieveCurrency(undefined as unknown as string)
} catch (e) {
error = e
}
expect(error.message).toEqual('"currencyCode" must be defined')
})
it("should return currency based on config select param", async () => {
const currency = await service.retrieveCurrency(code, {
select: ["code", "name"],
})
const serialized = JSON.parse(JSON.stringify(currency))
expect(serialized).toEqual({
code,
name,
})
})
})
describe("deleteCurrencies", () => {
const code = "USD"
it("should delete the currencies given an code successfully", async () => {
await service.deleteCurrencies([code])
const currencies = await service.listCurrencies({
code: [code],
})
expect(currencies).toHaveLength(0)
})
})
describe("updateCurrencies", () => {
const code = "USD"
it("should update the name of the currency successfully", async () => {
await service.updateCurrencies([
{
code,
name: "United States Pounds",
},
])
const currency = await service.retrieveCurrency(code)
expect(currency.name).toEqual("United States Pounds")
})
it("should throw an error when a code does not exist", async () => {
let error
try {
await service.updateCurrencies([
{
code: "does-not-exist",
name: "UK",
},
])
} catch (e) {
error = e
}
expect(error.message).toEqual(
'Currency with code "does-not-exist" not found'
)
})
})
describe("createCurrencies", () => {
it("should create a currency successfully", async () => {
await service.createCurrencies([
{
code: "TES",
name: "Test Dollars",
symbol: "TES1",
symbol_native: "TES2",
},
])
const [currency] = await service.listCurrencies({
code: ["TES"],
})
expect(currency).toEqual(
expect.objectContaining({
code: "TES",
name: "Test Dollars",
symbol: "TES1",
symbol_native: "TES2",
})
)
})
})
})
@@ -0,0 +1,6 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-integration-${tempName}`
}
process.env.MEDUSA_PRICING_DB_SCHEMA = "public"
@@ -0,0 +1,3 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -0,0 +1,6 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-pricing-test",
}
@@ -0,0 +1,18 @@
import { TestDatabaseUtils } from "medusa-test-utils"
import * as PricingModels from "@models"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = PricingModels as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper(
mikroOrmEntities,
pathToMigrations
)
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig(
mikroOrmEntities,
pathToMigrations
)
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -0,0 +1 @@
export * from "./database"
+21
View File
@@ -0,0 +1,21 @@
module.exports = {
moduleNameMapper: {
"^@models": "<rootDir>/src/models",
"^@services": "<rootDir>/src/services",
"^@repositories": "<rootDir>/src/repositories",
},
transform: {
"^.+\\.[jt]s?$": [
"ts-jest",
{
tsConfig: "tsconfig.spec.json",
isolatedModules: true,
},
],
},
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
+8
View File
@@ -0,0 +1,8 @@
import * as entities from "./src/models"
module.exports = {
entities: Object.values(entities),
schema: "public",
clientUrl: "postgres://postgres@localhost/medusa-pricing",
type: "postgresql",
}
+60
View File
@@ -0,0 +1,60 @@
{
"name": "@medusajs/pricing",
"version": "0.0.1",
"description": "Medusa Pricing module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"bin": {
"medusa-pricing-migrations-down": "dist/scripts/bin/run-migration-down.js",
"medusa-pricing-migrations-up": "dist/scripts/bin/run-migration-up.js",
"medusa-pricing-seed": "dist/scripts/bin/run-seed.js"
},
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/pricing"
},
"publishConfig": {
"access": "public"
},
"author": "Medusa",
"license": "MIT",
"scripts": {
"watch": "tsc --build --watch",
"watch:test": "tsc --build tsconfig.spec.json --watch",
"prepublishOnly": "cross-env NODE_ENV=production tsc --build && tsc-alias -p tsconfig.json",
"build": "rimraf dist && tsc --build && tsc-alias -p tsconfig.json",
"test": "jest --runInBand --bail --forceExit -- src/**/__tests__/**/*.ts",
"test:integration": "jest --runInBand --forceExit -- integration-tests/**/__tests__/**/*.ts",
"migration:generate": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:generate",
"migration:initial": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create --initial",
"migration:create": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create",
"migration:up": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:up",
"orm:cache:clear": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm cache:clear"
},
"devDependencies": {
"@mikro-orm/cli": "5.7.12",
"cross-env": "^5.2.1",
"jest": "^29.6.3",
"medusa-test-utils": "^1.1.40",
"rimraf": "^3.0.2",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.1",
"tsc-alias": "^1.8.6",
"typescript": "^5.1.6"
},
"dependencies": {
"@medusajs/modules-sdk": "^1.9.2",
"@medusajs/types": "^1.10.2",
"@medusajs/utils": "^1.9.7",
"@mikro-orm/core": "5.7.12",
"@mikro-orm/migrations": "5.7.12",
"@mikro-orm/postgresql": "5.7.12",
"awilix": "^8.0.0",
"dotenv": "^16.1.4",
"knex": "2.4.2"
}
}
+10
View File
@@ -0,0 +1,10 @@
import { moduleDefinition } from "./module-definition"
export default moduleDefinition
export * from "./scripts"
export * from "./initialize"
export * from "./types"
export * from "./loaders"
export * from "./models"
export * from "./services"
+31
View File
@@ -0,0 +1,31 @@
import {
ExternalModuleDeclaration,
InternalModuleDeclaration,
MedusaModule,
MODULE_PACKAGE_NAMES,
Modules,
} from "@medusajs/modules-sdk"
import { IPricingModuleService, ModulesSdkTypes } from "@medusajs/types"
import { moduleDefinition } from "../module-definition"
import { InitializeModuleInjectableDependencies } from "../types"
export const initialize = async (
options?:
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
| ExternalModuleDeclaration
| InternalModuleDeclaration,
injectedDependencies?: InitializeModuleInjectableDependencies
): Promise<IPricingModuleService> => {
const serviceKey = Modules.PRICING
const loaded = await MedusaModule.bootstrap<IPricingModuleService>(
serviceKey,
MODULE_PACKAGE_NAMES[Modules.PRICING],
options as InternalModuleDeclaration | ExternalModuleDeclaration,
moduleDefinition,
injectedDependencies
)
return loaded[serviceKey]
}
+38
View File
@@ -0,0 +1,38 @@
import { Modules } from "@medusajs/modules-sdk"
import { JoinerServiceConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { Currency } from "@models"
export enum LinkableKeys {
MONEY_AMOUNT_ID = "money_amount_id",
CURRENCY_CODE = "code",
}
export const entityNameToLinkableKeysMap: MapToConfig = {
[Currency.name]: [{ mapTo: LinkableKeys.CURRENCY_CODE, valueFrom: "code" }],
}
export const joinerConfig: JoinerServiceConfig = {
serviceName: Modules.PRICING,
primaryKeys: ["code"],
alias: [
// {
// name: "money_amount",
// },
// {
// name: "money_amounts",
// },
{
name: "currency",
args: {
methodSuffix: "Currencies",
},
},
{
name: "currencies",
args: {
methodSuffix: "Currencies",
},
},
],
}
@@ -0,0 +1,27 @@
import { InternalModuleDeclaration, LoaderOptions } from "@medusajs/modules-sdk"
import { ModulesSdkTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
import * as PricingModels from "../models"
export default async (
{
options,
container,
logger,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
>,
moduleDeclaration?: InternalModuleDeclaration
): Promise<void> => {
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
await ModulesSdkUtils.mikroOrmConnectionLoader({
entities,
container,
options,
moduleDeclaration,
logger,
})
}
+41
View File
@@ -0,0 +1,41 @@
import { ModulesSdkTypes } from "@medusajs/types"
import * as defaultRepositories from "@repositories"
import { BaseRepository, CurrencyRepository } from "@repositories"
import { CurrencyService } from "@services"
import { LoaderOptions } from "@medusajs/modules-sdk"
import { loadCustomRepositories } from "@medusajs/utils"
import { asClass } from "awilix"
export default async ({
container,
options,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
>): Promise<void> => {
const customRepositories = (
options as ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
)?.repositories
container.register({
currencyService: asClass(CurrencyService).singleton(),
})
if (customRepositories) {
loadCustomRepositories({
defaultRepositories,
customRepositories,
container,
})
} else {
loadDefaultRepositories({ container })
}
}
function loadDefaultRepositories({ container }) {
container.register({
baseRepository: asClass(BaseRepository).singleton(),
currencyRepository: asClass(CurrencyRepository).singleton(),
})
}
+2
View File
@@ -0,0 +1,2 @@
export * from "./connection"
export * from "./container"
@@ -0,0 +1,63 @@
{
"namespaces": [
"public"
],
"name": "public",
"tables": [
{
"columns": {
"code": {
"name": "code",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"symbol": {
"name": "symbol",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"symbol_native": {
"name": "symbol_native",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"name": {
"name": "name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
}
},
"name": "currency",
"schema": "public",
"indexes": [
{
"keyName": "currency_pkey",
"columnNames": [
"code"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
}
]
}
@@ -0,0 +1,9 @@
import { Migration } from '@mikro-orm/migrations';
export class Migration20230828182018 extends Migration {
async up(): Promise<void> {
this.addSql('create table "currency" ("code" text not null, "symbol" text not null, "symbol_native" text not null, "name" text not null, constraint "currency_pkey" primary key ("code"));');
}
}
+27
View File
@@ -0,0 +1,27 @@
import { Entity, PrimaryKey, Property } from "@mikro-orm/core"
@Entity({ tableName: "currency" })
class Currency {
@PrimaryKey({ columnType: "text" })
code!: string
@Property({ columnType: "text" })
symbol: string
@Property({ columnType: "text" })
symbol_native: string
@Property({ columnType: "text" })
name: string
// @Property({ persist: false })
// get includes_tax() {
// // TODO: This comes from a feature flag
// // Figure out how we're handling FF in modules
// // For now, returning default as true
// // This should also not fall on the hands of the model
// return true
// }
}
export default Currency
+1
View File
@@ -0,0 +1 @@
export { default as Currency } from "./currency"
+12
View File
@@ -0,0 +1,12 @@
import { ModuleExports } from "@medusajs/types"
import { PricingModuleService } from "@services"
import loadConnection from "./loaders/connection"
import loadContainer from "./loaders/container"
const service = PricingModuleService
const loaders = [loadContainer, loadConnection] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
}
@@ -0,0 +1,127 @@
import {
Context,
CreateCurrencyDTO,
DAL,
UpdateCurrencyDTO,
} from "@medusajs/types"
import { DALUtils, MedusaError } from "@medusajs/utils"
import {
LoadStrategy,
FilterQuery as MikroFilterQuery,
FindOptions as MikroOptions,
} from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Currency } from "@models"
export class CurrencyRepository extends DALUtils.MikroOrmBaseRepository {
protected readonly manager_: SqlEntityManager
constructor({ manager }: { manager: SqlEntityManager }) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
super(...arguments)
this.manager_ = manager
}
async find(
findOptions: DAL.FindOptions<Currency> = { where: {} },
context: Context = {}
): Promise<Currency[]> {
const manager = this.getActiveManager<SqlEntityManager>(context)
const findOptions_ = { ...findOptions }
findOptions_.options ??= {}
Object.assign(findOptions_.options, {
strategy: LoadStrategy.SELECT_IN,
})
return await manager.find(
Currency,
findOptions_.where as MikroFilterQuery<Currency>,
findOptions_.options as MikroOptions<Currency>
)
}
async findAndCount(
findOptions: DAL.FindOptions<Currency> = { where: {} },
context: Context = {}
): Promise<[Currency[], number]> {
const manager = this.getActiveManager<SqlEntityManager>(context)
const findOptions_ = { ...findOptions }
findOptions_.options ??= {}
Object.assign(findOptions_.options, {
strategy: LoadStrategy.SELECT_IN,
})
return await manager.findAndCount(
Currency,
findOptions_.where as MikroFilterQuery<Currency>,
findOptions_.options as MikroOptions<Currency>
)
}
async delete(codes: string[], context: Context = {}): Promise<void> {
const manager = this.getActiveManager<SqlEntityManager>(context)
await manager.nativeDelete(Currency, { code: { $in: codes } }, {})
}
async create(
data: CreateCurrencyDTO[],
context: Context = {}
): Promise<Currency[]> {
const manager = this.getActiveManager<SqlEntityManager>(context)
const currencies = data.map((currencyData) => {
return manager.create(Currency, currencyData)
})
manager.persist(currencies)
return currencies
}
async update(
data: UpdateCurrencyDTO[],
context: Context = {}
): Promise<Currency[]> {
const manager = this.getActiveManager<SqlEntityManager>(context)
const currencyCodes = data.map((currencyData) => currencyData.code)
const existingCurrencies = await this.find(
{
where: {
code: {
$in: currencyCodes,
},
},
},
context
)
const existingCurrencyMap = new Map(
existingCurrencies.map<[string, Currency]>((currency) => [
currency.code,
currency,
])
)
const currencies = data.map((currencyData) => {
const existingCurrency = existingCurrencyMap.get(currencyData.code)
if (!existingCurrency) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`Currency with code "${currencyData.code}" not found`
)
}
return manager.assign(existingCurrency, currencyData)
})
manager.persist(currencies)
return currencies
}
}
@@ -0,0 +1,2 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
export { CurrencyRepository } from "./currency"
@@ -0,0 +1,8 @@
#!/usr/bin/env node
export default (async () => {
const { revertMigration } = await import("../migration-down")
const { config } = await import("dotenv")
config()
await revertMigration()
})()
@@ -0,0 +1,8 @@
#!/usr/bin/env node
export default (async () => {
const { runMigrations } = await import("../migration-up")
const { config } = await import("dotenv")
config()
await runMigrations()
})()
@@ -0,0 +1,19 @@
#!/usr/bin/env node
import { EOL } from "os"
import { run } from "../seed"
const args = process.argv
const path = args.pop() as string
export default (async () => {
const { config } = await import("dotenv")
config()
if (!path) {
throw new Error(
`filePath is required.${EOL}Example: medusa-pricing-seed <filePath>`
)
}
await run({ path })
})()
+2
View File
@@ -0,0 +1,2 @@
export * from "./migration-up"
export * from "./migration-down"
@@ -0,0 +1,39 @@
import * as PricingModels from "@models"
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
/**
* This script is only valid for mikro orm managers. If a user provide a custom manager
* he is in charge of reverting the migrations.
* @param options
* @param logger
* @param moduleDeclaration
*/
export async function revertMigration({
options,
logger,
}: Pick<
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>,
"options" | "logger"
> = {}) {
logger ??= console as unknown as Logger
const dbData = ModulesSdkUtils.loadDatabaseConfig("pricing", options)!
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
const orm = await DALUtils.mikroOrmCreateConnection(dbData, entities)
try {
const migrator = orm.getMigrator()
await migrator.down()
logger?.info("Pricing module migration executed")
} catch (error) {
logger?.error(`Pricing module migration failed to run - Error: ${error}`)
}
await orm.close()
}
@@ -0,0 +1,43 @@
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
import * as PricingModels from "@models"
/**
* This script is only valid for mikro orm managers. If a user provide a custom manager
* he is in charge of running the migrations.
* @param options
* @param logger
* @param moduleDeclaration
*/
export async function runMigrations({
options,
logger,
}: Pick<
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>,
"options" | "logger"
> = {}) {
logger ??= console as unknown as Logger
const dbData = ModulesSdkUtils.loadDatabaseConfig("pricing", options)!
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
const orm = await DALUtils.mikroOrmCreateConnection(dbData, entities)
try {
const migrator = orm.getMigrator()
const pendingMigrations = await migrator.getPendingMigrations()
logger.info(`Running pending migrations: ${pendingMigrations}`)
await migrator.up({
migrations: pendingMigrations.map((m) => m.name),
})
logger.info("Pricing module migration executed")
} catch (error) {
logger.error(`Pricing module migration failed to run - Error: ${error}`)
}
await orm.close()
}
+64
View File
@@ -0,0 +1,64 @@
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema, RequiredEntityData } from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import * as PricingModels from "@models"
import { EOL } from "os"
import { resolve } from "path"
export async function run({
options,
logger,
path,
}: Partial<
Pick<
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>,
"options" | "logger"
>
> & {
path: string
}) {
logger ??= console as unknown as Logger
logger.info(`Loading seed data from ${path}...`)
const { currenciesData } = await import(resolve(process.cwd(), path)).catch(
(e) => {
logger?.error(
`Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following currenciesData.${EOL}${e}`
)
throw e
}
)
const dbData = ModulesSdkUtils.loadDatabaseConfig("pricing", options)!
const entities = Object.values(PricingModels) as unknown as EntitySchema[]
const orm = await DALUtils.mikroOrmCreateConnection(dbData, entities)
const manager = orm.em.fork()
try {
logger.info("Inserting currencies")
await createCurrencies(manager, currenciesData)
} catch (e) {
logger.error(
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
)
}
await orm.close(true)
}
async function createCurrencies(
manager: SqlEntityManager,
data: RequiredEntityData<PricingModels.Currency>[]
) {
const currencies: any[] = data.map((currencyData) => {
return manager.create(PricingModels.Currency, currencyData)
})
await manager.persistAndFlush(currencies)
return currencies
}
@@ -0,0 +1,21 @@
import { CurrencyService } from "@services"
import { asClass, asValue, createContainer } from "awilix"
export const nonExistingCurrencyCode = "non-existing-code"
export const mockContainer = createContainer()
mockContainer.register({
transaction: asValue(async (task) => await task()),
currencyRepository: asValue({
find: jest.fn().mockImplementation(async ({ where: { code } }) => {
if (code === nonExistingCurrencyCode) {
return []
}
return [{}]
}),
findAndCount: jest.fn().mockResolvedValue([[], 0]),
getFreshManager: jest.fn().mockResolvedValue({}),
}),
currencyService: asClass(CurrencyService),
})
@@ -0,0 +1,203 @@
import {
mockContainer,
nonExistingCurrencyCode,
} from "../__fixtures__/currency"
const code = "existing-currency"
describe("Currency service", function () {
beforeEach(function () {
jest.clearAllMocks()
})
it("should retrieve a currency", async function () {
const currencyService = mockContainer.resolve("currencyService")
const currencyRepository = mockContainer.resolve("currencyRepository")
await currencyService.retrieve(code)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {
code,
},
options: {
fields: undefined,
limit: 15,
offset: undefined,
populate: [],
},
},
expect.any(Object)
)
})
it("should fail to retrieve a currency", async function () {
const currencyService = mockContainer.resolve("currencyService")
const currencyRepository = mockContainer.resolve("currencyRepository")
const err = await currencyService
.retrieve(nonExistingCurrencyCode)
.catch((e) => e)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {
code: nonExistingCurrencyCode,
},
options: {
fields: undefined,
limit: 15,
offset: undefined,
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
expect(err.message).toBe(
`Currency with code: ${nonExistingCurrencyCode} was not found`
)
})
it("should list currencys", async function () {
const currencyService = mockContainer.resolve("currencyService")
const currencyRepository = mockContainer.resolve("currencyRepository")
const filters = {}
const config = {
relations: [],
}
await currencyService.list(filters, config)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {},
options: {
fields: undefined,
limit: 15,
offset: undefined,
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
})
it("should list currencys with filters", async function () {
const currencyService = mockContainer.resolve("currencyService")
const currencyRepository = mockContainer.resolve("currencyRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: [],
}
await currencyService.list(filters, config)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: undefined,
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
})
it("should list currencys with filters and relations", async function () {
const currencyService = mockContainer.resolve("currencyService")
const currencyRepository = mockContainer.resolve("currencyRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: ["tags"],
}
await currencyService.list(filters, config)
expect(currencyRepository.find).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: undefined,
withDeleted: undefined,
populate: ["tags"],
},
},
expect.any(Object)
)
})
it("should list and count the currencys with filters and relations", async function () {
const currencyService = mockContainer.resolve("currencyService")
const currencyRepository = mockContainer.resolve("currencyRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: ["tags"],
}
await currencyService.listAndCount(filters, config)
expect(currencyRepository.findAndCount).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: undefined,
withDeleted: undefined,
populate: ["tags"],
},
},
expect.any(Object)
)
})
})
+107
View File
@@ -0,0 +1,107 @@
import { Context, DAL, FindConfig, PricingTypes } from "@medusajs/types"
import {
InjectManager,
InjectTransactionManager,
MedusaContext,
ModulesSdkUtils,
retrieveEntity,
} from "@medusajs/utils"
import { Currency } from "@models"
import { CurrencyRepository } from "@repositories"
import { doNotForceTransaction, shouldForceTransaction } from "@medusajs/utils"
type InjectedDependencies = {
currencyRepository: DAL.RepositoryService
}
export default class CurrencyService<TEntity extends Currency = Currency> {
protected readonly currencyRepository_: DAL.RepositoryService
constructor({ currencyRepository }: InjectedDependencies) {
this.currencyRepository_ = currencyRepository
}
@InjectManager("currencyRepository_")
async retrieve(
currencyCode: string,
config: FindConfig<PricingTypes.CurrencyDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity> {
return (await retrieveEntity<Currency, PricingTypes.CurrencyDTO>({
id: currencyCode,
identifierColumn: "code",
entityName: Currency.name,
repository: this.currencyRepository_,
config,
sharedContext,
})) as TEntity
}
@InjectManager("currencyRepository_")
async list(
filters: PricingTypes.FilterableCurrencyProps = {},
config: FindConfig<PricingTypes.CurrencyDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity[]> {
return (await this.currencyRepository_.find(
this.buildQueryForList(filters, config),
sharedContext
)) as TEntity[]
}
@InjectManager("currencyRepository_")
async listAndCount(
filters: PricingTypes.FilterableCurrencyProps = {},
config: FindConfig<PricingTypes.CurrencyDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<[TEntity[], number]> {
return (await this.currencyRepository_.findAndCount(
this.buildQueryForList(filters, config),
sharedContext
)) as [TEntity[], number]
}
private buildQueryForList(
filters: PricingTypes.FilterableCurrencyProps = {},
config: FindConfig<PricingTypes.CurrencyDTO> = {}
) {
const queryOptions = ModulesSdkUtils.buildQuery<Currency>(filters, config)
if (filters.code) {
queryOptions.where["code"] = { $in: filters.code }
}
return queryOptions
}
@InjectTransactionManager(shouldForceTransaction, "currencyRepository_")
async create(
data: PricingTypes.CreateCurrencyDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity[]> {
return (await (this.currencyRepository_ as CurrencyRepository).create(
data,
sharedContext
)) as TEntity[]
}
@InjectTransactionManager(shouldForceTransaction, "currencyRepository_")
async update(
data: PricingTypes.UpdateCurrencyDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity[]> {
return (await (this.currencyRepository_ as CurrencyRepository).update(
data,
sharedContext
)) as TEntity[]
}
@InjectTransactionManager(doNotForceTransaction, "currencyRepository_")
async delete(
ids: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<void> {
await this.currencyRepository_.delete(ids, sharedContext)
}
}
+2
View File
@@ -0,0 +1,2 @@
export { default as CurrencyService } from "./currency"
export { default as PricingModuleService } from "./pricing-module"
@@ -0,0 +1,141 @@
import {
Context,
DAL,
FindConfig,
InternalModuleDeclaration,
JoinerServiceConfig,
PricingTypes,
} from "@medusajs/types"
import { Currency } from "@models"
import { CurrencyService } from "@services"
import {
InjectManager,
InjectTransactionManager,
MedusaContext,
} from "@medusajs/utils"
import { shouldForceTransaction } from "@medusajs/utils"
import { joinerConfig } from "../joiner-config"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
currencyService: CurrencyService<any>
}
export default class PricingModuleService<TCurrency extends Currency = Currency>
implements PricingTypes.IPricingModuleService
{
protected baseRepository_: DAL.RepositoryService
protected readonly currencyService_: CurrencyService<TCurrency>
constructor(
{ baseRepository, currencyService }: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
this.baseRepository_ = baseRepository
this.currencyService_ = currencyService
}
__joinerConfig(): JoinerServiceConfig {
return joinerConfig
}
@InjectManager("baseRepository_")
async retrieveCurrency(
code: string,
config: FindConfig<PricingTypes.CurrencyDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<PricingTypes.CurrencyDTO> {
const currency = await this.currencyService_.retrieve(
code,
config,
sharedContext
)
return this.baseRepository_.serialize<PricingTypes.CurrencyDTO>(currency, {
populate: true,
})
}
@InjectManager("baseRepository_")
async listCurrencies(
filters: PricingTypes.FilterableCurrencyProps = {},
config: FindConfig<PricingTypes.CurrencyDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<PricingTypes.CurrencyDTO[]> {
const currencies = await this.currencyService_.list(
filters,
config,
sharedContext
)
return this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
currencies,
{
populate: true,
}
)
}
@InjectManager("baseRepository_")
async listAndCountCurrencies(
filters: PricingTypes.FilterableCurrencyProps = {},
config: FindConfig<PricingTypes.CurrencyDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<[PricingTypes.CurrencyDTO[], number]> {
const [currencies, count] = await this.currencyService_.listAndCount(
filters,
config,
sharedContext
)
return [
await this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
currencies,
{
populate: true,
}
),
count,
]
}
@InjectTransactionManager(shouldForceTransaction, "baseRepository_")
async createCurrencies(
data: PricingTypes.CreateCurrencyDTO[],
@MedusaContext() sharedContext: Context = {}
) {
const currencies = await this.currencyService_.create(data, sharedContext)
return this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
currencies,
{
populate: true,
}
)
}
@InjectTransactionManager(shouldForceTransaction, "baseRepository_")
async updateCurrencies(
data: PricingTypes.UpdateCurrencyDTO[],
@MedusaContext() sharedContext: Context = {}
) {
const currencies = await this.currencyService_.update(data, sharedContext)
return this.baseRepository_.serialize<PricingTypes.CurrencyDTO[]>(
currencies,
{
populate: true,
}
)
}
@InjectTransactionManager(shouldForceTransaction, "baseRepository_")
async deleteCurrencies(
currencyCodes: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<void> {
await this.currencyService_.delete(currencyCodes, sharedContext)
}
}
+5
View File
@@ -0,0 +1,5 @@
import { Logger } from "@medusajs/types"
export type InitializeModuleInjectableDependencies = {
logger?: Logger
}
+36
View File
@@ -0,0 +1,36 @@
{
"compilerOptions": {
"lib": ["es2020"],
"target": "es2020",
"outDir": "./dist",
"esModuleInterop": true,
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": false,
"noImplicitReturns": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"allowJs": true,
"skipLibCheck": true,
"downlevelIteration": true, // to use ES5 specific tooling
"baseUrl": ".",
"resolveJsonModule": true,
"paths": {
"@models": ["./src/models"],
"@services": ["./src/services"],
"@repositories": ["./src/repositories"]
}
},
"include": ["src"],
"exclude": [
"dist",
"./src/**/__tests__",
"./src/**/__mocks__",
"./src/**/__fixtures__",
"node_modules"
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"include": ["src", "integration-tests"],
"exclude": ["node_modules", "dist"]
}