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:
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 = {}
|
||||
Reference in New Issue
Block a user