feat: Add currency module and remove currency models from region and pricing modules (#6536)

What:
- Creates a new currency module
- Removes currency model from the pricing module
- Removes currency model from region module
This commit is contained in:
Stevche Radevski authored and GitHub committed 2024-02-29 15:09:59 +00:00
1 parent 06f706a51a
commit dc025302a1
102 files changed
+1502 -2128

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
/dist
node_modules
.DS_store
.env*
.env
*.sql
+1
View File
@@ -0,0 +1 @@
# Currency Module
Whitespace-only changes.
@@ -0,0 +1,199 @@
import { Modules } from "@medusajs/modules-sdk"
import { ICurrencyModuleService } from "@medusajs/types"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
jest.setTimeout(100000)
moduleIntegrationTestRunner({
moduleName: Modules.CURRENCY,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<ICurrencyModuleService>) => {
describe("Currency Module Service", () => {
describe("list", () => {
it("list currencies", async () => {
const currenciesResult = await service.list({}, { take: null })
expect(currenciesResult).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: "cad",
name: "Canadian Dollar",
}),
expect.objectContaining({
code: "usd",
name: "US Dollar",
}),
])
)
})
it("list currencies by code", async () => {
const currenciesResult = await service.list(
{ code: ["usd"] },
{ take: null }
)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "usd",
name: "US Dollar",
}),
])
})
it("list currencies by code regardless of case-sensitivity", async () => {
const currenciesResult = await service.list(
{ code: ["Usd"] },
{ take: null }
)
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(
{},
{ take: null }
)
expect(count).toEqual(120)
expect(currenciesResult).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: "cad",
name: "Canadian Dollar",
}),
expect.objectContaining({
code: "usd",
name: "US Dollar",
}),
])
)
})
it("should return currencies and count when filtered", async () => {
const [currenciesResult, count] = await service.listAndCount(
{
code: ["usd"],
},
{ take: null }
)
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: 5, take: 1 }
)
expect(count).toEqual(120)
expect(currenciesResult).toEqual([
expect.objectContaining({
code: "aud",
name: "Australian 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(120)
expect(serialized).toEqual([
{
code: "aed",
},
])
})
})
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 return currency for the given code in a case-insensitive manner", async () => {
const currency = await service.retrieve(code.toUpperCase())
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("currency - code 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,
})
})
})
})
},
})
+20
View File
@@ -0,0 +1,20 @@
module.exports = {
moduleNameMapper: {
"^@models": "<rootDir>/src/models",
"^@services": "<rootDir>/src/services",
"^@repositories": "<rootDir>/src/repositories",
"^@types": "<rootDir>/src/types",
},
transform: {
"^.+\\.[jt]s?$": [
"ts-jest",
{
tsConfig: "tsconfig.spec.json",
isolatedModules: true,
},
],
},
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
}
@@ -0,0 +1,8 @@
import * as entities from "./src/models"
module.exports = {
entities: Object.values(entities),
schema: "public",
clientUrl: "postgres://postgres@localhost/medusa-currency",
type: "postgresql",
}
+61
View File
@@ -0,0 +1,61 @@
{
"name": "@medusajs/currency",
"version": "0.1.0",
"description": "Medusa Currency module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"engines": {
"node": ">=16"
},
"bin": {
"medusa-currency-seed": "dist/scripts/bin/run-seed.js"
},
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/currency"
},
"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.9.7",
"cross-env": "^5.2.1",
"jest": "^29.6.3",
"medusa-test-utils": "workspace:^",
"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.12.4",
"@medusajs/types": "^1.11.8",
"@medusajs/utils": "^1.11.1",
"@mikro-orm/core": "5.9.7",
"@mikro-orm/migrations": "5.9.7",
"@mikro-orm/postgresql": "5.9.7",
"awilix": "^8.0.0",
"dotenv": "^16.1.4",
"knex": "2.4.2"
}
}
+14
View File
@@ -0,0 +1,14 @@
import { moduleDefinition } from "./module-definition"
import { initializeFactory, Modules } from "@medusajs/modules-sdk"
export * from "./types"
export * from "./models"
export * from "./services"
export const initialize = initializeFactory({
moduleName: Modules.CURRENCY,
moduleDefinition,
})
export const runMigrations = moduleDefinition.runMigrations
export const revertMigration = moduleDefinition.revertMigration
export default moduleDefinition
+29
View File
@@ -0,0 +1,29 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import Currency from "./models/currency"
export const LinkableKeys: Record<string, string> = {}
const entityLinkableKeysMap: MapToConfig = {}
Object.entries(LinkableKeys).forEach(([key, value]) => {
entityLinkableKeysMap[value] ??= []
entityLinkableKeysMap[value].push({
mapTo: key,
valueFrom: key.split("_").pop()!,
})
})
export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap
export const joinerConfig: ModuleJoinerConfig = {
serviceName: Modules.CURRENCY,
primaryKeys: ["code"],
linkableKeys: LinkableKeys,
alias: [
{
name: ["currency", "currencies"],
args: { entity: Currency.name },
},
],
} as ModuleJoinerConfig
@@ -0,0 +1,30 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { ModulesSdkTypes, LoaderOptions } from "@medusajs/types"
import { defaultCurrencies } from "@medusajs/utils"
import { Currency } from "@models"
export default async ({
container,
options,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
>): Promise<void> => {
try {
const {
currencyService_,
}: { currencyService_: ModulesSdkTypes.InternalModuleService<Currency> } =
container.resolve(ModuleRegistrationName.CURRENCY)
const normalizedCurrencies = Object.values(defaultCurrencies).map((c) => ({
...c,
code: c.code.toLowerCase(),
}))
const resp = await currencyService_.upsert(normalizedCurrencies)
console.log(`Loaded ${resp.length} currencies`)
} catch (error) {
console.error(
`Failed to load currencies, skipping loader. Original error: ${error.message}`
)
}
}
@@ -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 InitialSetup20240228133303 extends Migration {
async up(): Promise<void> {
this.addSql(`create table if not exists "currency"
("code" text not null, "symbol" text not null, "symbol_native" text not null, "name" text not null,
constraint "currency_pkey" primary key ("code"));`)
}
}
+18
View File
@@ -0,0 +1,18 @@
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
}
export default Currency
+1
View File
@@ -0,0 +1 @@
export { default as Currency } from "./currency"
@@ -0,0 +1,45 @@
import { ModuleExports } from "@medusajs/types"
import * as ModuleServices from "@services"
import { CurrencyModuleService } from "@services"
import { Modules } from "@medusajs/modules-sdk"
import * as Models from "@models"
import * as ModuleModels from "@models"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as ModuleRepositories from "@repositories"
import initialDataLoader from "./loaders/initial-data"
const migrationScriptOptions = {
moduleName: Modules.CURRENCY,
models: Models,
pathToMigrations: __dirname + "/migrations",
}
const runMigrations = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({
moduleModels: ModuleModels,
moduleRepositories: ModuleRepositories,
moduleServices: ModuleServices,
})
const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({
moduleName: Modules.CURRENCY,
moduleModels: Object.values(Models),
migrationsPath: __dirname + "/migrations",
})
const service = CurrencyModuleService
const loaders = [containerLoader, connectionLoader, initialDataLoader] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
revertMigration,
runMigrations,
}
@@ -0,0 +1 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
@@ -0,0 +1,29 @@
#!/usr/bin/env node
import { ModulesSdkUtils } from "@medusajs/utils"
import { Modules } from "@medusajs/modules-sdk"
import * as Models from "@models"
import { EOL } from "os"
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-currency-seed <filePath>`
)
}
const run = ModulesSdkUtils.buildSeedScript({
moduleName: Modules.CURRENCY,
models: Models,
pathToMigrations: __dirname + "/../../migrations",
seedHandler: async ({ manager, data }) => {
// TODO: Add seed logic
},
})
await run({ path })
})()
@@ -0,0 +1,5 @@
describe("noop", function () {
it("should run", function () {
expect(true).toBe(true)
})
})
@@ -0,0 +1,131 @@
import {
DAL,
InternalModuleDeclaration,
ModuleJoinerConfig,
ModulesSdkTypes,
ICurrencyModuleService,
CurrencyTypes,
Context,
FindConfig,
FilterableCurrencyProps,
BaseFilterable,
} from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { Currency } from "@models"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
const generateMethodForModels = []
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
currencyService: ModulesSdkTypes.InternalModuleService<any>
}
export default class CurrencyModuleService<TEntity extends Currency = Currency>
extends ModulesSdkUtils.abstractModuleServiceFactory<
InjectedDependencies,
CurrencyTypes.CurrencyDTO,
{
Currency: { dto: CurrencyTypes.CurrencyDTO }
}
>(Currency, generateMethodForModels, entityNameToLinkableKeysMap)
implements ICurrencyModuleService
{
protected baseRepository_: DAL.RepositoryService
protected readonly currencyService_: ModulesSdkTypes.InternalModuleService<TEntity>
constructor(
{ baseRepository, currencyService }: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
// @ts-ignore
super(...arguments)
this.baseRepository_ = baseRepository
this.currencyService_ = currencyService
}
__joinerConfig(): ModuleJoinerConfig {
return joinerConfig
}
retrieve(
code: string,
config?: FindConfig<CurrencyTypes.CurrencyDTO>,
sharedContext?: Context
): Promise<CurrencyTypes.CurrencyDTO> {
return this.currencyService_.retrieve(
code?.toLowerCase(),
config,
sharedContext
)
}
list(
filters?: FilterableCurrencyProps,
config?: FindConfig<CurrencyTypes.CurrencyDTO>,
sharedContext?: Context
): Promise<CurrencyTypes.CurrencyDTO[]> {
return this.currencyService_.list(
CurrencyModuleService.normalizeFilters(filters),
config,
sharedContext
)
}
listAndCount(
filters?: FilterableCurrencyProps,
config?: FindConfig<CurrencyTypes.CurrencyDTO>,
sharedContext?: Context
): Promise<[CurrencyTypes.CurrencyDTO[], number]> {
return this.currencyService_.listAndCount(
CurrencyModuleService.normalizeFilters(filters),
config,
sharedContext
)
}
protected static normalizeFilters(
filters: FilterableCurrencyProps | undefined
): FilterableCurrencyProps | undefined {
return normalizeFilterable<
CurrencyTypes.CurrencyDTO,
FilterableCurrencyProps
>(filters, (fieldName, value) => {
if (fieldName === "code" && !!value) {
return value.toLowerCase()
}
return value
})
}
}
// TODO: Move normalizer support to `buildQuery` so we don't even need to override the list/retrieve methods just for normalization
const normalizeFilterable = <TModel, TFilter extends BaseFilterable<TFilter>>(
filters: TFilter | undefined,
normalizer: (fieldName: keyof TModel, value: any) => any
): TFilter | undefined => {
if (!filters) {
return filters
}
const normalizedFilters = {} as TFilter
for (const key in filters) {
if (key === "$and" || key === "$or") {
normalizedFilters[key] = (filters[key] as any).map((filter) =>
normalizeFilterable(filter, normalizer)
)
} else if (filters[key] !== undefined) {
if (Array.isArray(filters[key])) {
normalizedFilters[key] = (filters[key] as any).map((val) =>
normalizer(key as any, val)
)
} else {
normalizedFilters[key] = normalizer(key as any, filters[key])
}
}
}
return normalizedFilters
}
+1
View File
@@ -0,0 +1 @@
export { default as CurrencyModuleService } from "./currency-module-service"
+6
View File
@@ -0,0 +1,6 @@
import { IEventBusModuleService, Logger } from "@medusajs/types"
export type InitializeModuleInjectableDependencies = {
logger?: Logger
eventBusService?: IEventBusModuleService
}
+37
View File
@@ -0,0 +1,37 @@
{
"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"],
"@types": ["./src/types"]
}
},
"include": ["src"],
"exclude": [
"dist",
"./src/**/__tests__",
"./src/**/__mocks__",
"./src/**/__fixtures__",
"node_modules"
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"include": ["src", "integration-tests"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"sourceMap": true
}
}