feat(user): Init user module (#6293)
* init user module * add migration * update module with latest utils * pr ready * make interface types interfaces
This commit is contained in:
@@ -7,55 +7,58 @@ import {
|
||||
import { upperCaseFirst } from "@medusajs/utils"
|
||||
|
||||
export enum Modules {
|
||||
LINK = "linkModules",
|
||||
EVENT_BUS = "eventBus",
|
||||
STOCK_LOCATION = "stockLocationService",
|
||||
INVENTORY = "inventoryService",
|
||||
CACHE = "cacheService",
|
||||
PRODUCT = "productService",
|
||||
PRICING = "pricingService",
|
||||
PROMOTION = "promotion",
|
||||
AUTH = "auth",
|
||||
WORKFLOW_ENGINE = "workflows",
|
||||
SALES_CHANNEL = "salesChannel",
|
||||
CACHE = "cacheService",
|
||||
CART = "cart",
|
||||
CUSTOMER = "customer",
|
||||
EVENT_BUS = "eventBus",
|
||||
INVENTORY = "inventoryService",
|
||||
LINK = "linkModules",
|
||||
PAYMENT = "payment",
|
||||
PRICING = "pricingService",
|
||||
PRODUCT = "productService",
|
||||
PROMOTION = "promotion",
|
||||
SALES_CHANNEL = "salesChannel",
|
||||
STOCK_LOCATION = "stockLocationService",
|
||||
USER = "user",
|
||||
WORKFLOW_ENGINE = "workflows",
|
||||
REGION = "region",
|
||||
}
|
||||
|
||||
export enum ModuleRegistrationName {
|
||||
EVENT_BUS = "eventBusModuleService",
|
||||
STOCK_LOCATION = "stockLocationService",
|
||||
INVENTORY = "inventoryService",
|
||||
CACHE = "cacheService",
|
||||
PRODUCT = "productModuleService",
|
||||
PRICING = "pricingModuleService",
|
||||
PROMOTION = "promotionModuleService",
|
||||
AUTH = "authModuleService",
|
||||
WORKFLOW_ENGINE = "workflowsModuleService",
|
||||
SALES_CHANNEL = "salesChannelModuleService",
|
||||
CACHE = "cacheService",
|
||||
CART = "cartModuleService",
|
||||
CUSTOMER = "customerModuleService",
|
||||
EVENT_BUS = "eventBusModuleService",
|
||||
INVENTORY = "inventoryService",
|
||||
PAYMENT = "paymentModuleService",
|
||||
PRICING = "pricingModuleService",
|
||||
PRODUCT = "productModuleService",
|
||||
PROMOTION = "promotionModuleService",
|
||||
SALES_CHANNEL = "salesChannelModuleService",
|
||||
STOCK_LOCATION = "stockLocationService",
|
||||
USER = "userModuleService",
|
||||
WORKFLOW_ENGINE = "workflowsModuleService",
|
||||
REGION = "regionModuleService",
|
||||
}
|
||||
|
||||
export const MODULE_PACKAGE_NAMES = {
|
||||
[Modules.LINK]: "@medusajs/link-modules",
|
||||
[Modules.PRODUCT]: "@medusajs/product",
|
||||
[Modules.EVENT_BUS]: "@medusajs/event-bus-local",
|
||||
[Modules.STOCK_LOCATION]: "@medusajs/stock-location",
|
||||
[Modules.INVENTORY]: "@medusajs/inventory",
|
||||
[Modules.CACHE]: "@medusajs/cache-inmemory",
|
||||
[Modules.PRICING]: "@medusajs/pricing",
|
||||
[Modules.PROMOTION]: "@medusajs/promotion",
|
||||
[Modules.AUTH]: "@medusajs/auth",
|
||||
[Modules.WORKFLOW_ENGINE]: "@medusajs/workflow-engine-inmemory",
|
||||
[Modules.SALES_CHANNEL]: "@medusajs/sales-channel",
|
||||
[Modules.CACHE]: "@medusajs/cache-inmemory",
|
||||
[Modules.CART]: "@medusajs/cart",
|
||||
[Modules.CUSTOMER]: "@medusajs/customer",
|
||||
[Modules.EVENT_BUS]: "@medusajs/event-bus-local",
|
||||
[Modules.INVENTORY]: "@medusajs/inventory",
|
||||
[Modules.LINK]: "@medusajs/link-modules",
|
||||
[Modules.PAYMENT]: "@medusajs/payment",
|
||||
[Modules.PRICING]: "@medusajs/pricing",
|
||||
[Modules.PRODUCT]: "@medusajs/product",
|
||||
[Modules.PROMOTION]: "@medusajs/promotion",
|
||||
[Modules.SALES_CHANNEL]: "@medusajs/sales-channel",
|
||||
[Modules.STOCK_LOCATION]: "@medusajs/stock-location",
|
||||
[Modules.USER]: "@medusajs/user",
|
||||
[Modules.WORKFLOW_ENGINE]: "@medusajs/workflow-engine-inmemory",
|
||||
[Modules.REGION]: "@medusajs/region",
|
||||
}
|
||||
|
||||
@@ -231,6 +234,19 @@ export const ModulesDefinition: { [key: string | Modules]: ModuleDefinition } =
|
||||
resources: MODULE_RESOURCE_TYPE.SHARED,
|
||||
},
|
||||
},
|
||||
[Modules.USER]: {
|
||||
key: Modules.USER,
|
||||
registrationName: ModuleRegistrationName.USER,
|
||||
defaultPackage: false,
|
||||
label: upperCaseFirst(ModuleRegistrationName.USER),
|
||||
isRequired: false,
|
||||
isQueryable: true,
|
||||
dependencies: ["logger"],
|
||||
defaultModuleDeclaration: {
|
||||
scope: MODULE_SCOPE.INTERNAL,
|
||||
resources: MODULE_RESOURCE_TYPE.SHARED,
|
||||
},
|
||||
},
|
||||
[Modules.REGION]: {
|
||||
key: Modules.REGION,
|
||||
registrationName: ModuleRegistrationName.REGION,
|
||||
|
||||
@@ -17,5 +17,6 @@ export * as SalesChannelTypes from "./sales-channel"
|
||||
export * as SearchTypes from "./search"
|
||||
export * as StockLocationTypes from "./stock-location"
|
||||
export * as TransactionBaseTypes from "./transaction-base"
|
||||
export * as UserTypes from "./user"
|
||||
export * as WorkflowTypes from "./workflow"
|
||||
|
||||
|
||||
@@ -26,5 +26,6 @@ export * from "./search"
|
||||
export * from "./shared-context"
|
||||
export * from "./stock-location"
|
||||
export * from "./transaction-base"
|
||||
export * from "./user"
|
||||
export * from "./workflow"
|
||||
|
||||
|
||||
5
packages/types/src/user/common.ts
Normal file
5
packages/types/src/user/common.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export type UserDTO = {
|
||||
id: string
|
||||
}
|
||||
|
||||
export type FilterableUserProps = {}
|
||||
3
packages/types/src/user/index.ts
Normal file
3
packages/types/src/user/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from "./common"
|
||||
export * from "./mutations"
|
||||
export * from "./service"
|
||||
6
packages/types/src/user/mutations.ts
Normal file
6
packages/types/src/user/mutations.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export interface CreateUserDTO {
|
||||
id?: string
|
||||
}
|
||||
export interface UpdateUserDTO {
|
||||
id: string
|
||||
}
|
||||
36
packages/types/src/user/service.ts
Normal file
36
packages/types/src/user/service.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { CreateUserDTO, UpdateUserDTO } from "./mutations"
|
||||
import { FilterableUserProps, UserDTO } from "./common"
|
||||
|
||||
import { Context } from "../shared-context"
|
||||
import { FindConfig } from "../common"
|
||||
import { IModuleService } from "../modules-sdk"
|
||||
|
||||
export interface IUserModuleService extends IModuleService {
|
||||
retrieve(
|
||||
id: string,
|
||||
config?: FindConfig<UserDTO>,
|
||||
sharedContext?: Context
|
||||
): Promise<UserDTO>
|
||||
|
||||
list(
|
||||
filters?: FilterableUserProps,
|
||||
config?: FindConfig<UserDTO>,
|
||||
sharedContext?: Context
|
||||
): Promise<UserDTO[]>
|
||||
|
||||
listAndCount(
|
||||
filters?: FilterableUserProps,
|
||||
config?: FindConfig<UserDTO>,
|
||||
sharedContext?: Context
|
||||
): Promise<[UserDTO[], number]>
|
||||
|
||||
create(data: CreateUserDTO[], sharedContext?: Context): Promise<UserDTO[]>
|
||||
|
||||
create(data: CreateUserDTO, sharedContext?: Context): Promise<UserDTO>
|
||||
|
||||
update(data: UpdateUserDTO[], sharedContext?: Context): Promise<UserDTO[]>
|
||||
|
||||
update(data: UpdateUserDTO, sharedContext?: Context): Promise<UserDTO>
|
||||
|
||||
delete(ids: string[], sharedContext?: Context): Promise<void>
|
||||
}
|
||||
6
packages/user/.gitignore
vendored
Normal file
6
packages/user/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/dist
|
||||
node_modules
|
||||
.DS_store
|
||||
.env*
|
||||
.env
|
||||
*.sql
|
||||
3
packages/user/README.md
Normal file
3
packages/user/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# User Module
|
||||
|
||||
The User Module is Medusa’s user engine.
|
||||
16
packages/user/integration-tests/__fixtures__/user.ts
Normal file
16
packages/user/integration-tests/__fixtures__/user.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { User } from "@models"
|
||||
|
||||
export const createUsers = async (
|
||||
manager: SqlEntityManager,
|
||||
userData = [{ id: "1" }]
|
||||
) => {
|
||||
const users: User[] = []
|
||||
|
||||
for (const user of userData) {
|
||||
const usr = manager.create(User, user)
|
||||
users.push(usr)
|
||||
}
|
||||
|
||||
await manager.persistAndFlush(users)
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { IUserModuleService } from "@medusajs/types/dist/user"
|
||||
import { MikroOrmWrapper } from "../../../utils"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { createUsers } from "../../../__fixtures__/user"
|
||||
import { getInitModuleConfig } from "../../../utils/get-init-module-config"
|
||||
import { initModules } from "medusa-test-utils"
|
||||
|
||||
jest.setTimeout(30000)
|
||||
|
||||
describe("UserModuleService - User", () => {
|
||||
let service: IUserModuleService
|
||||
let testManager: SqlEntityManager
|
||||
let shutdownFunc: () => Promise<void>
|
||||
|
||||
beforeAll(async () => {
|
||||
const initModulesConfig = getInitModuleConfig()
|
||||
|
||||
const { medusaApp, shutdown } = await initModules(initModulesConfig)
|
||||
|
||||
service = medusaApp.modules[Modules.USER]
|
||||
|
||||
shutdownFunc = shutdown
|
||||
})
|
||||
|
||||
beforeEach(async () => {
|
||||
await MikroOrmWrapper.setupDatabase()
|
||||
testManager = MikroOrmWrapper.forkManager()
|
||||
|
||||
await createUsers(testManager)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await MikroOrmWrapper.clearDatabase()
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await shutdownFunc()
|
||||
})
|
||||
|
||||
describe("listUsers", () => {
|
||||
it("should list users", async () => {
|
||||
const users = await service.list()
|
||||
const serialized = JSON.parse(JSON.stringify(users))
|
||||
|
||||
expect(serialized).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it("should list users by id", async () => {
|
||||
const users = await service.list({
|
||||
id: ["1"],
|
||||
})
|
||||
|
||||
expect(users).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("listAndCountUsers", () => {
|
||||
it("should list and count users", async () => {
|
||||
const [users, count] = await service.listAndCount()
|
||||
const serialized = JSON.parse(JSON.stringify(users))
|
||||
|
||||
expect(count).toEqual(1)
|
||||
expect(serialized).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it("should listAndCount Users by id", async () => {
|
||||
const [Users, count] = await service.listAndCount({
|
||||
id: "1",
|
||||
})
|
||||
|
||||
expect(count).toEqual(1)
|
||||
expect(Users).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("retrieveUser", () => {
|
||||
const id = "1"
|
||||
|
||||
it("should return an user for the given id", async () => {
|
||||
const user = await service.retrieve(id)
|
||||
|
||||
expect(user).toEqual(
|
||||
expect.objectContaining({
|
||||
id,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should throw an error when an user with the given id does not exist", async () => {
|
||||
let error
|
||||
|
||||
try {
|
||||
await service.retrieve("does-not-exist")
|
||||
} catch (e) {
|
||||
error = e
|
||||
}
|
||||
|
||||
expect(error.message).toEqual(
|
||||
"User with id: does-not-exist was not found"
|
||||
)
|
||||
})
|
||||
|
||||
it("should throw an error when a userId is not provided", async () => {
|
||||
let error
|
||||
|
||||
try {
|
||||
await service.retrieve(undefined as unknown as string)
|
||||
} catch (e) {
|
||||
error = e
|
||||
}
|
||||
|
||||
expect(error.message).toEqual("user - id must be defined")
|
||||
})
|
||||
|
||||
it("should return user based on config select param", async () => {
|
||||
const User = await service.retrieve(id, {
|
||||
select: ["id"],
|
||||
})
|
||||
|
||||
const serialized = JSON.parse(JSON.stringify(User))
|
||||
|
||||
expect(serialized).toEqual({
|
||||
id,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("deleteUser", () => {
|
||||
const id = "1"
|
||||
|
||||
it("should delete the Users given an id successfully", async () => {
|
||||
await service.delete([id])
|
||||
|
||||
const users = await service.list({
|
||||
id: [id],
|
||||
})
|
||||
|
||||
expect(users).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe("updateUser", () => {
|
||||
it("should throw an error when a id does not exist", async () => {
|
||||
let error
|
||||
|
||||
try {
|
||||
await service.update([
|
||||
{
|
||||
id: "does-not-exist",
|
||||
},
|
||||
])
|
||||
} catch (e) {
|
||||
error = e
|
||||
}
|
||||
|
||||
expect(error.message).toEqual('User with id "does-not-exist" not found')
|
||||
})
|
||||
})
|
||||
|
||||
describe("createUser", () => {
|
||||
it("should create a User successfully", async () => {
|
||||
await service.create([
|
||||
{
|
||||
id: "2",
|
||||
},
|
||||
])
|
||||
|
||||
const [User, count] = await service.listAndCount({
|
||||
id: ["2"],
|
||||
})
|
||||
|
||||
expect(count).toEqual(1)
|
||||
expect(User[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: "2",
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
6
packages/user/integration-tests/setup-env.js
Normal file
6
packages/user/integration-tests/setup-env.js
Normal file
@@ -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-user-integration-${tempName}`
|
||||
}
|
||||
|
||||
process.env.MEDUSA_USER_DB_SCHEMA = "public"
|
||||
3
packages/user/integration-tests/setup.js
Normal file
3
packages/user/integration-tests/setup.js
Normal file
@@ -0,0 +1,3 @@
|
||||
import { JestUtils } from "medusa-test-utils"
|
||||
|
||||
JestUtils.afterAllHookDropDatabase()
|
||||
6
packages/user/integration-tests/utils/config.ts
Normal file
6
packages/user/integration-tests/utils/config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { ModuleServiceInitializeOptions } from "@medusajs/types"
|
||||
|
||||
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
|
||||
schema: "public",
|
||||
clientUrl: "medusa-user-test",
|
||||
}
|
||||
18
packages/user/integration-tests/utils/database.ts
Normal file
18
packages/user/integration-tests/utils/database.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as UserModels from "@models"
|
||||
|
||||
import { TestDatabaseUtils } from "medusa-test-utils"
|
||||
|
||||
const pathToMigrations = "../../src/migrations"
|
||||
const mikroOrmEntities = UserModels 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,33 @@
|
||||
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
|
||||
|
||||
import { DB_URL } from "./database"
|
||||
|
||||
export function getInitModuleConfig() {
|
||||
const moduleOptions = {
|
||||
defaultAdapterOptions: {
|
||||
database: {
|
||||
clientUrl: DB_URL,
|
||||
schema: process.env.MEDUSA_USER_DB_SCHEMA,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const injectedDependencies = {}
|
||||
|
||||
const modulesConfig_ = {
|
||||
[Modules.USER]: {
|
||||
definition: ModulesDefinition[Modules.USER],
|
||||
options: moduleOptions,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
injectedDependencies,
|
||||
modulesConfig: modulesConfig_,
|
||||
databaseConfig: {
|
||||
clientUrl: DB_URL,
|
||||
schema: process.env.MEDUSA_USER_DB_SCHEMA,
|
||||
},
|
||||
joinerConfig: [],
|
||||
}
|
||||
}
|
||||
2
packages/user/integration-tests/utils/index.ts
Normal file
2
packages/user/integration-tests/utils/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./config"
|
||||
export * from "./database"
|
||||
22
packages/user/jest.config.js
Normal file
22
packages/user/jest.config.js
Normal file
@@ -0,0 +1,22 @@
|
||||
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/"],
|
||||
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
|
||||
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
|
||||
}
|
||||
8
packages/user/mikro-orm.config.dev.ts
Normal file
8
packages/user/mikro-orm.config.dev.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import * as entities from "./src/models"
|
||||
|
||||
module.exports = {
|
||||
entities: Object.values(entities),
|
||||
schema: "public",
|
||||
clientUrl: "postgres://postgres@localhost/medusa-user",
|
||||
type: "postgresql",
|
||||
}
|
||||
61
packages/user/package.json
Normal file
61
packages/user/package.json
Normal file
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "@medusajs/user",
|
||||
"version": "0.0.1",
|
||||
"description": "Medusa Users module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"bin": {
|
||||
"medusa-user-seed": "dist/scripts/bin/run-seed.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/medusajs/medusa",
|
||||
"directory": "packages/user"
|
||||
},
|
||||
"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": "^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.12.7",
|
||||
"@medusajs/types": "^1.11.11",
|
||||
"@medusajs/utils": "^1.11.4",
|
||||
"@mikro-orm/core": "5.9.7",
|
||||
"@mikro-orm/migrations": "5.9.7",
|
||||
"@mikro-orm/postgresql": "5.9.7",
|
||||
"awilix": "^8.0.0",
|
||||
"dotenv": "16.3.1",
|
||||
"knex": "2.4.2"
|
||||
}
|
||||
}
|
||||
11
packages/user/src/index.ts
Normal file
11
packages/user/src/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import {
|
||||
moduleDefinition,
|
||||
revertMigration,
|
||||
runMigrations,
|
||||
} from "./module-definition"
|
||||
|
||||
export default moduleDefinition
|
||||
export { revertMigration, runMigrations }
|
||||
|
||||
export * from "./initialize"
|
||||
export * from "./loaders"
|
||||
31
packages/user/src/initialize/index.ts
Normal file
31
packages/user/src/initialize/index.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
ExternalModuleDeclaration,
|
||||
InternalModuleDeclaration,
|
||||
MODULE_PACKAGE_NAMES,
|
||||
MedusaModule,
|
||||
Modules,
|
||||
} from "@medusajs/modules-sdk"
|
||||
import { IUserModuleService, ModulesSdkTypes } from "@medusajs/types"
|
||||
|
||||
import { InitializeModuleInjectableDependencies } from "../types"
|
||||
import { moduleDefinition } from "../module-definition"
|
||||
|
||||
export const initialize = async (
|
||||
options?:
|
||||
| ModulesSdkTypes.ModuleBootstrapDeclaration
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions,
|
||||
injectedDependencies?: InitializeModuleInjectableDependencies
|
||||
): Promise<IUserModuleService> => {
|
||||
const loaded = await MedusaModule.bootstrap<IUserModuleService>({
|
||||
moduleKey: Modules.USER,
|
||||
defaultPath: MODULE_PACKAGE_NAMES[Modules.USER],
|
||||
declaration: options as
|
||||
| InternalModuleDeclaration
|
||||
| ExternalModuleDeclaration,
|
||||
injectedDependencies,
|
||||
moduleExports: moduleDefinition,
|
||||
})
|
||||
|
||||
return loaded[Modules.USER]
|
||||
}
|
||||
31
packages/user/src/joiner-config.ts
Normal file
31
packages/user/src/joiner-config.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { User } from "@models"
|
||||
import { MapToConfig } from "@medusajs/utils"
|
||||
import { ModuleJoinerConfig } from "@medusajs/types"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
|
||||
export const LinkableKeys = {
|
||||
user_id: User.name,
|
||||
}
|
||||
|
||||
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.USER,
|
||||
primaryKeys: ["id"],
|
||||
linkableKeys: LinkableKeys,
|
||||
alias: {
|
||||
name: ["user", "users"],
|
||||
args: {
|
||||
entity: User.name,
|
||||
},
|
||||
},
|
||||
}
|
||||
36
packages/user/src/loaders/connection.ts
Normal file
36
packages/user/src/loaders/connection.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import * as UserModels from "../models"
|
||||
|
||||
import {
|
||||
InternalModuleDeclaration,
|
||||
LoaderOptions,
|
||||
Modules,
|
||||
} from "@medusajs/modules-sdk"
|
||||
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
import { ModulesSdkTypes } from "@medusajs/types"
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
|
||||
export default async (
|
||||
{
|
||||
options,
|
||||
container,
|
||||
logger,
|
||||
}: LoaderOptions<
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
>,
|
||||
moduleDeclaration?: InternalModuleDeclaration
|
||||
): Promise<void> => {
|
||||
const entities = Object.values(UserModels) as unknown as EntitySchema[]
|
||||
const pathToMigrations = __dirname + "/../migrations"
|
||||
|
||||
await ModulesSdkUtils.mikroOrmConnectionLoader({
|
||||
moduleName: Modules.USER,
|
||||
entities,
|
||||
container,
|
||||
options,
|
||||
moduleDeclaration,
|
||||
logger,
|
||||
pathToMigrations,
|
||||
})
|
||||
}
|
||||
10
packages/user/src/loaders/container.ts
Normal file
10
packages/user/src/loaders/container.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
import * as ModuleModels from "@models"
|
||||
import * as ModuleRepositories from "@repositories"
|
||||
import * as ModuleServices from "@services"
|
||||
|
||||
export default ModulesSdkUtils.moduleContainerLoaderFactory({
|
||||
moduleModels: ModuleModels,
|
||||
moduleRepositories: ModuleRepositories,
|
||||
moduleServices: ModuleServices,
|
||||
})
|
||||
2
packages/user/src/loaders/index.ts
Normal file
2
packages/user/src/loaders/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./connection"
|
||||
export * from "./container"
|
||||
36
packages/user/src/migrations/.snapshot-medusa-user.json
Normal file
36
packages/user/src/migrations/.snapshot-medusa-user.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"namespaces": [
|
||||
"public"
|
||||
],
|
||||
"name": "public",
|
||||
"tables": [
|
||||
{
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"mappedType": "text"
|
||||
}
|
||||
},
|
||||
"name": "user",
|
||||
"schema": "public",
|
||||
"indexes": [
|
||||
{
|
||||
"keyName": "user_pkey",
|
||||
"columnNames": [
|
||||
"id"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": true,
|
||||
"unique": true
|
||||
}
|
||||
],
|
||||
"checks": [],
|
||||
"foreignKeys": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
13
packages/user/src/migrations/Migration20240201081925.ts
Normal file
13
packages/user/src/migrations/Migration20240201081925.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
export class Migration20240201081925 extends Migration {
|
||||
|
||||
async up(): Promise<void> {
|
||||
this.addSql('create table "user" ("id" text not null, constraint "user_pkey" primary key ("id"));');
|
||||
}
|
||||
|
||||
async down(): Promise<void> {
|
||||
this.addSql('drop table if exists "user" cascade;');
|
||||
}
|
||||
|
||||
}
|
||||
1
packages/user/src/models/index.ts
Normal file
1
packages/user/src/models/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as User } from "./user"
|
||||
25
packages/user/src/models/user.ts
Normal file
25
packages/user/src/models/user.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import {
|
||||
BeforeCreate,
|
||||
Entity,
|
||||
OnInit,
|
||||
PrimaryKey,
|
||||
} from "@mikro-orm/core"
|
||||
|
||||
import { generateEntityId } from "@medusajs/utils"
|
||||
|
||||
|
||||
@Entity()
|
||||
export default class User {
|
||||
@PrimaryKey({ columnType: "text" })
|
||||
id!: string
|
||||
|
||||
@BeforeCreate()
|
||||
onCreate() {
|
||||
this.id = generateEntityId(this.id, "user")
|
||||
}
|
||||
|
||||
@OnInit()
|
||||
onInit() {
|
||||
this.id = generateEntityId(this.id, "user")
|
||||
}
|
||||
}
|
||||
31
packages/user/src/module-definition.ts
Normal file
31
packages/user/src/module-definition.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import * as Models from "@models"
|
||||
|
||||
import { UserModuleService } from "@services"
|
||||
import { ModuleExports } from "@medusajs/types"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
import loadConnection from "./loaders/connection"
|
||||
import loadContainer from "./loaders/container"
|
||||
|
||||
const migrationScriptOptions = {
|
||||
moduleName: Modules.USER,
|
||||
models: Models,
|
||||
pathToMigrations: __dirname + "/migrations",
|
||||
}
|
||||
|
||||
export const runMigrations = ModulesSdkUtils.buildMigrationScript(
|
||||
migrationScriptOptions
|
||||
)
|
||||
export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
|
||||
migrationScriptOptions
|
||||
)
|
||||
|
||||
const service = UserModuleService
|
||||
const loaders = [loadContainer, loadConnection] as any
|
||||
|
||||
export const moduleDefinition: ModuleExports = {
|
||||
service,
|
||||
loaders,
|
||||
runMigrations,
|
||||
revertMigration,
|
||||
}
|
||||
1
packages/user/src/repositories/index.ts
Normal file
1
packages/user/src/repositories/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
|
||||
19
packages/user/src/scripts/bin/run-seed.ts
Normal file
19
packages/user/src/scripts/bin/run-seed.ts
Normal file
@@ -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-user-seed <filePath>`
|
||||
)
|
||||
}
|
||||
|
||||
await run({ path })
|
||||
})()
|
||||
58
packages/user/src/scripts/seed.ts
Normal file
58
packages/user/src/scripts/seed.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import * as UserModels from "@models"
|
||||
|
||||
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
|
||||
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
|
||||
|
||||
import { EOL } from "os"
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
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 { userData } = 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: userData.${EOL}${e}`
|
||||
)
|
||||
throw e
|
||||
})
|
||||
|
||||
const dbData = ModulesSdkUtils.loadDatabaseConfig(Modules.USER, options)!
|
||||
const entities = Object.values(UserModels) as unknown as EntitySchema[]
|
||||
const pathToMigrations = __dirname + "/../migrations"
|
||||
|
||||
const orm = await DALUtils.mikroOrmCreateConnection(
|
||||
dbData,
|
||||
entities,
|
||||
pathToMigrations
|
||||
)
|
||||
|
||||
const manager = orm.em.fork()
|
||||
|
||||
try {
|
||||
logger.info("Seeding user data..")
|
||||
|
||||
// TODO: implement user seed data
|
||||
// await createUsers(manager, usersData)
|
||||
} catch (e) {
|
||||
logger.error(
|
||||
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
|
||||
)
|
||||
}
|
||||
|
||||
await orm.close(true)
|
||||
}
|
||||
5
packages/user/src/services/__tests__/index.spec.ts
Normal file
5
packages/user/src/services/__tests__/index.spec.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
describe("Noop test", () => {
|
||||
it("noop check", async () => {
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
})
|
||||
1
packages/user/src/services/index.ts
Normal file
1
packages/user/src/services/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as UserModuleService } from "./user-module"
|
||||
113
packages/user/src/services/user-module.ts
Normal file
113
packages/user/src/services/user-module.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import {
|
||||
Context,
|
||||
DAL,
|
||||
InternalModuleDeclaration,
|
||||
ModuleJoinerConfig,
|
||||
UserTypes,
|
||||
CreateUserDTO,
|
||||
UpdateUserDTO,
|
||||
UserDTO,
|
||||
ModulesSdkTypes,
|
||||
} from "@medusajs/types"
|
||||
import {
|
||||
InjectManager,
|
||||
InjectTransactionManager,
|
||||
MedusaContext,
|
||||
ModulesSdkUtils,
|
||||
} from "@medusajs/utils"
|
||||
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
|
||||
|
||||
import { User } from "@models"
|
||||
|
||||
type InjectedDependencies = {
|
||||
baseRepository: DAL.RepositoryService
|
||||
userService: ModulesSdkTypes.InternalModuleService<any>
|
||||
}
|
||||
|
||||
const generateMethodForModels = []
|
||||
|
||||
export default class UserModuleService<TUser extends User = User>
|
||||
extends ModulesSdkUtils.abstractModuleServiceFactory<
|
||||
InjectedDependencies,
|
||||
UserDTO,
|
||||
{}
|
||||
>(User, generateMethodForModels, entityNameToLinkableKeysMap)
|
||||
implements UserTypes.IUserModuleService
|
||||
{
|
||||
__joinerConfig(): ModuleJoinerConfig {
|
||||
return joinerConfig
|
||||
}
|
||||
|
||||
protected baseRepository_: DAL.RepositoryService
|
||||
|
||||
protected readonly userService_: ModulesSdkTypes.InternalModuleService<TUser>
|
||||
|
||||
constructor(
|
||||
{ userService, baseRepository }: InjectedDependencies,
|
||||
protected readonly moduleDeclaration: InternalModuleDeclaration
|
||||
) {
|
||||
// @ts-ignore
|
||||
super(...arguments)
|
||||
|
||||
this.baseRepository_ = baseRepository
|
||||
this.userService_ = userService
|
||||
}
|
||||
|
||||
create(data: CreateUserDTO[], sharedContext?: Context): Promise<UserDTO[]>
|
||||
create(data: CreateUserDTO, sharedContext?: Context): Promise<UserDTO>
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
async create(
|
||||
data: CreateUserDTO[] | CreateUserDTO,
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<UserTypes.UserDTO | UserTypes.UserDTO[]> {
|
||||
const input = Array.isArray(data) ? data : [data]
|
||||
|
||||
const users = await this.create_(input, sharedContext)
|
||||
|
||||
const serializedUsers = await this.baseRepository_.serialize<
|
||||
UserTypes.UserDTO[]
|
||||
>(users, {
|
||||
populate: true,
|
||||
})
|
||||
|
||||
return Array.isArray(data) ? serializedUsers : serializedUsers[0]
|
||||
}
|
||||
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
protected async create_(
|
||||
data: CreateUserDTO[],
|
||||
@MedusaContext() sharedContext: Context
|
||||
): Promise<TUser[]> {
|
||||
return await this.userService_.create(data, sharedContext)
|
||||
}
|
||||
|
||||
update(data: UpdateUserDTO[], sharedContext?: Context): Promise<UserDTO[]>
|
||||
update(data: UpdateUserDTO, sharedContext?: Context): Promise<UserDTO>
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
async update(
|
||||
data: UpdateUserDTO | UpdateUserDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<UserTypes.UserDTO | UserTypes.UserDTO[]> {
|
||||
const input = Array.isArray(data) ? data : [data]
|
||||
|
||||
const updatedUsers = await this.update_(input, sharedContext)
|
||||
|
||||
const serializedUsers = await this.baseRepository_.serialize<
|
||||
UserTypes.UserDTO[]
|
||||
>(updatedUsers, {
|
||||
populate: true,
|
||||
})
|
||||
|
||||
return Array.isArray(data) ? serializedUsers : serializedUsers[0]
|
||||
}
|
||||
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
protected async update_(
|
||||
data: UpdateUserDTO[],
|
||||
@MedusaContext() sharedContext: Context
|
||||
): Promise<TUser[]> {
|
||||
return await this.userService_.update(data, sharedContext)
|
||||
}
|
||||
}
|
||||
7
packages/user/src/types/index.ts
Normal file
7
packages/user/src/types/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Logger } from "@medusajs/types"
|
||||
|
||||
export type InitializeModuleInjectableDependencies = {
|
||||
logger?: Logger
|
||||
}
|
||||
|
||||
export * as ServiceTypes from "./services"
|
||||
1
packages/user/src/types/services/index.ts
Normal file
1
packages/user/src/types/services/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./user"
|
||||
13
packages/user/src/types/services/user.ts
Normal file
13
packages/user/src/types/services/user.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export type UserDTO = {
|
||||
id: string
|
||||
}
|
||||
|
||||
export type CreateUserDTO = {
|
||||
id?: string
|
||||
}
|
||||
|
||||
export type UpdateUserDTO = {
|
||||
id: string
|
||||
}
|
||||
|
||||
export type FilterableUserProps = {}
|
||||
50
packages/user/tsconfig.json
Normal file
50
packages/user/tsconfig.json
Normal file
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"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
packages/user/tsconfig.spec.json
Normal file
8
packages/user/tsconfig.spec.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"include": ["src", "integration-tests"],
|
||||
"exclude": ["node_modules", "dist"],
|
||||
"compilerOptions": {
|
||||
"sourceMap": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user