feat(types,module-sdk): setup authentication module skeleton (#5943)
**What** - add authentication module skeleton
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
import { moduleDefinition } from "./module-definition"
|
||||
|
||||
export default moduleDefinition
|
||||
|
||||
export * from "./initialize"
|
||||
export * from "./loaders"
|
||||
export * from "./scripts"
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
ExternalModuleDeclaration,
|
||||
InternalModuleDeclaration,
|
||||
MedusaModule,
|
||||
MODULE_PACKAGE_NAMES,
|
||||
Modules,
|
||||
} from "@medusajs/modules-sdk"
|
||||
import { IAuthenticationModuleService, ModulesSdkTypes } from "@medusajs/types"
|
||||
import { moduleDefinition } from "../module-definition"
|
||||
import { InitializeModuleInjectableDependencies } from "../types"
|
||||
|
||||
export const initialize = async (
|
||||
options?: ModulesSdkTypes.ModuleBootstrapDeclaration,
|
||||
injectedDependencies?: InitializeModuleInjectableDependencies
|
||||
): Promise<IAuthenticationModuleService> => {
|
||||
const loaded = await MedusaModule.bootstrap<IAuthenticationModuleService>({
|
||||
moduleKey: Modules.AUTHENTICATION,
|
||||
defaultPath: MODULE_PACKAGE_NAMES[Modules.AUTHENTICATION],
|
||||
declaration: options as
|
||||
| InternalModuleDeclaration
|
||||
| ExternalModuleDeclaration, // TODO: Add provider configuration
|
||||
injectedDependencies,
|
||||
moduleExports: moduleDefinition,
|
||||
})
|
||||
|
||||
return loaded[Modules.AUTHENTICATION]
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { ModuleJoinerConfig } from "@medusajs/types"
|
||||
import { MapToConfig } from "@medusajs/utils"
|
||||
import { AuthUser } from "@models"
|
||||
|
||||
export const LinkableKeys = {
|
||||
auth_user_id: AuthUser.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.AUTHENTICATION,
|
||||
primaryKeys: ["id"],
|
||||
linkableKeys: LinkableKeys,
|
||||
alias: {
|
||||
name: ["auth_user", "auth_users"],
|
||||
args: {
|
||||
entity: AuthUser.name,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
InternalModuleDeclaration,
|
||||
LoaderOptions,
|
||||
Modules,
|
||||
} from "@medusajs/modules-sdk"
|
||||
import { ModulesSdkTypes } from "@medusajs/types"
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
import * as AuthenticationModules from "../models"
|
||||
|
||||
export default async (
|
||||
{
|
||||
options,
|
||||
container,
|
||||
logger,
|
||||
}: LoaderOptions<
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
>,
|
||||
moduleDeclaration?: InternalModuleDeclaration
|
||||
): Promise<void> => {
|
||||
const entities = Object.values(
|
||||
AuthenticationModules
|
||||
) as unknown as EntitySchema[]
|
||||
const pathToMigrations = __dirname + "/../migrations"
|
||||
|
||||
await ModulesSdkUtils.mikroOrmConnectionLoader({
|
||||
moduleName: Modules.AUTHENTICATION,
|
||||
entities,
|
||||
container,
|
||||
options,
|
||||
moduleDeclaration,
|
||||
logger,
|
||||
pathToMigrations,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import * as defaultRepositories from "@repositories"
|
||||
|
||||
import { LoaderOptions } from "@medusajs/modules-sdk"
|
||||
import { ModulesSdkTypes } from "@medusajs/types"
|
||||
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({
|
||||
// authenticationService: asClass(defaultServices.AuthenticationService).singleton(),
|
||||
})
|
||||
|
||||
if (customRepositories) {
|
||||
loadCustomRepositories({
|
||||
defaultRepositories,
|
||||
customRepositories,
|
||||
container,
|
||||
})
|
||||
} else {
|
||||
loadDefaultRepositories({ container })
|
||||
}
|
||||
}
|
||||
|
||||
function loadDefaultRepositories({ container }) {
|
||||
container.register({
|
||||
baseRepository: asClass(defaultRepositories.BaseRepository).singleton(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./connection"
|
||||
export * from "./container"
|
||||
@@ -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": "auth_user",
|
||||
"schema": "public",
|
||||
"indexes": [
|
||||
{
|
||||
"keyName": "auth_user_pkey",
|
||||
"columnNames": [
|
||||
"id"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": true,
|
||||
"unique": true
|
||||
}
|
||||
],
|
||||
"checks": [],
|
||||
"foreignKeys": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
export class Migration20231220132440 extends Migration {
|
||||
|
||||
async up(): Promise<void> {
|
||||
this.addSql('create table "auth_user" ("id" text not null, constraint "auth_user_pkey" primary key ("id"));');
|
||||
}
|
||||
|
||||
async down(): Promise<void> {
|
||||
this.addSql('drop table if exists "auth_user" cascade;');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { generateEntityId } from "@medusajs/utils"
|
||||
import { BeforeCreate, Entity, OnInit, PrimaryKey } from "@mikro-orm/core"
|
||||
|
||||
@Entity()
|
||||
export default class AuthUser {
|
||||
@PrimaryKey({ columnType: "text" })
|
||||
id!: string
|
||||
|
||||
@BeforeCreate()
|
||||
onCreate() {
|
||||
this.id = generateEntityId(this.id, "authusr")
|
||||
}
|
||||
|
||||
@OnInit()
|
||||
onInit() {
|
||||
this.id = generateEntityId(this.id, "authusr")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default as AuthUser } from "./auth-user"
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ModuleExports } from "@medusajs/types"
|
||||
import { AuthenticationModuleService } from "@services"
|
||||
import loadConnection from "./loaders/connection"
|
||||
import loadContainer from "./loaders/container"
|
||||
|
||||
const service = AuthenticationModuleService
|
||||
const loaders = [loadContainer, loadConnection] as any
|
||||
|
||||
export const moduleDefinition: ModuleExports = {
|
||||
service,
|
||||
loaders,
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
|
||||
@@ -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-authentication-seed <filePath>`
|
||||
)
|
||||
}
|
||||
|
||||
await run({ path })
|
||||
})()
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./migration-up"
|
||||
export * from "./migration-down"
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Modules } from "@medusajs/modules-sdk";
|
||||
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types";
|
||||
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils";
|
||||
import { EntitySchema } from "@mikro-orm/core";
|
||||
import * as AuthenticationModels from "@models";
|
||||
|
||||
/**
|
||||
* 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(
|
||||
Modules.AUTHENTICATION,
|
||||
options
|
||||
)!
|
||||
const entities = Object.values(
|
||||
AuthenticationModels
|
||||
) as unknown as EntitySchema[]
|
||||
const pathToMigrations = __dirname + "/../migrations"
|
||||
|
||||
const orm = await DALUtils.mikroOrmCreateConnection(
|
||||
dbData,
|
||||
entities,
|
||||
pathToMigrations
|
||||
)
|
||||
|
||||
try {
|
||||
const migrator = orm.getMigrator()
|
||||
await migrator.down()
|
||||
|
||||
logger?.info("Authentication module migration executed")
|
||||
} catch (error) {
|
||||
logger?.error(
|
||||
`Authentication module migration failed to run - Error: ${error}`
|
||||
)
|
||||
}
|
||||
|
||||
await orm.close()
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Modules } from "@medusajs/modules-sdk";
|
||||
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types";
|
||||
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils";
|
||||
import { EntitySchema } from "@mikro-orm/core";
|
||||
import * as AuthenticationModels 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(
|
||||
Modules.AUTHENTICATION,
|
||||
options
|
||||
)!
|
||||
const entities = Object.values(
|
||||
AuthenticationModels
|
||||
) as unknown as EntitySchema[]
|
||||
const pathToMigrations = __dirname + "/../migrations"
|
||||
|
||||
const orm = await DALUtils.mikroOrmCreateConnection(
|
||||
dbData,
|
||||
entities,
|
||||
pathToMigrations
|
||||
)
|
||||
|
||||
try {
|
||||
const migrator = orm.getMigrator()
|
||||
|
||||
const pendingMigrations = await migrator.getPendingMigrations()
|
||||
logger.info(
|
||||
`Running pending migrations: ${JSON.stringify(
|
||||
pendingMigrations,
|
||||
null,
|
||||
2
|
||||
)}`
|
||||
)
|
||||
|
||||
await migrator.up({
|
||||
migrations: pendingMigrations.map((m) => m.name),
|
||||
})
|
||||
|
||||
logger.info("Authentication module migration executed")
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`Authentication module migration failed to run - Error: ${error}`
|
||||
)
|
||||
}
|
||||
|
||||
await orm.close()
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
|
||||
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
import * as AuthenticationModels 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 { authenticationData } = 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: authenticationData.${EOL}${e}`
|
||||
)
|
||||
throw e
|
||||
})
|
||||
|
||||
const dbData = ModulesSdkUtils.loadDatabaseConfig(
|
||||
Modules.AUTHENTICATION,
|
||||
options
|
||||
)!
|
||||
const entities = Object.values(
|
||||
AuthenticationModels
|
||||
) 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 authentication data..")
|
||||
|
||||
// TODO: implement authentication seed data
|
||||
// await createAuthUsers(manager, authUsersData)
|
||||
} catch (e) {
|
||||
logger.error(
|
||||
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
|
||||
)
|
||||
}
|
||||
|
||||
await orm.close(true)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
describe("Noop test", () => {
|
||||
it("noop check", async () => {
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
AuthenticationTypes,
|
||||
DAL,
|
||||
InternalModuleDeclaration,
|
||||
ModuleJoinerConfig,
|
||||
} from "@medusajs/types"
|
||||
|
||||
import { AuthUser } from "@models"
|
||||
|
||||
import { joinerConfig } from "../joiner-config"
|
||||
|
||||
type InjectedDependencies = {
|
||||
baseRepository: DAL.RepositoryService
|
||||
}
|
||||
|
||||
export default class AuthenticationModuleService<
|
||||
TAuthUser extends AuthUser = AuthUser
|
||||
> implements AuthenticationTypes.IAuthenticationModuleService
|
||||
{
|
||||
protected baseRepository_: DAL.RepositoryService
|
||||
|
||||
constructor(
|
||||
{ baseRepository }: InjectedDependencies,
|
||||
protected readonly moduleDeclaration: InternalModuleDeclaration
|
||||
) {
|
||||
this.baseRepository_ = baseRepository
|
||||
}
|
||||
|
||||
__joinerConfig(): ModuleJoinerConfig {
|
||||
return joinerConfig
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default as AuthenticationModuleService } from "./authentication-module"
|
||||
@@ -0,0 +1,5 @@
|
||||
import { Logger } from "@medusajs/types"
|
||||
|
||||
export type InitializeModuleInjectableDependencies = {
|
||||
logger?: Logger
|
||||
}
|
||||
Reference in New Issue
Block a user