Chore/rm main entity concept (#7709)

**What**
Update the `MedusaService` class, factory and types to remove the concept of main modules. The idea being that all method will be explicitly named and suffixes to represent the object you are trying to manipulate.
This pr also includes various fixes in different modules

Co-authored-by: Stevche Radevski <4820812+sradevski@users.noreply.github.com>
Co-authored-by: Oli Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
Adrien de Peretti
2024-06-19 15:02:16 +02:00
committed by GitHub
parent 2895ccfba8
commit 48963f55ef
533 changed files with 6469 additions and 9769 deletions

View File

@@ -2,7 +2,7 @@ import { Modules } from "@medusajs/modules-sdk"
import { IApiKeyModuleService } from "@medusajs/types"
import { ApiKeyType } from "@medusajs/utils"
import crypto from "crypto"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { moduleIntegrationTestRunner } from "medusa-test-utils"
import {
createPublishableKeyFixture,
createSecretKeyFixture,
@@ -33,12 +33,9 @@ const mockSecretKeyBytes = () => {
})
}
moduleIntegrationTestRunner({
moduleIntegrationTestRunner<IApiKeyModuleService>({
moduleName: Modules.API_KEY,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IApiKeyModuleService>) => {
testSuite: ({ service }) => {
afterEach(() => {
jest.restoreAllMocks()
})
@@ -47,7 +44,9 @@ moduleIntegrationTestRunner({
describe("creating a publishable API key", () => {
it("should create it successfully", async function () {
mockPublishableKeyBytes()
const apiKey = await service.create(createPublishableKeyFixture)
const apiKey = await service.createApiKeys(
createPublishableKeyFixture
)
expect(apiKey).toEqual(
expect.objectContaining({
@@ -69,7 +68,7 @@ moduleIntegrationTestRunner({
describe("creating a secret API key", () => {
it("should get created successfully", async function () {
mockSecretKeyBytes()
const apiKey = await service.create(createSecretKeyFixture)
const apiKey = await service.createApiKeys(createSecretKeyFixture)
expect(apiKey).toEqual(
expect.objectContaining({
@@ -89,14 +88,17 @@ moduleIntegrationTestRunner({
it("should only allow creating one active token", async function () {
await expect(
service.create([createSecretKeyFixture, createSecretKeyFixture])
service.createApiKeys([
createSecretKeyFixture,
createSecretKeyFixture,
])
).rejects.toThrow(
"You can only create one secret key at a time. You tried to create 2 secret keys."
)
await service.create(createSecretKeyFixture)
await service.createApiKeys(createSecretKeyFixture)
const err = await service
.create(createSecretKeyFixture)
.createApiKeys(createSecretKeyFixture)
.catch((e) => e)
expect(err.message).toEqual(
"You can only have one active secret key a time. Revoke or delete your existing key before creating a new one."
@@ -104,7 +106,9 @@ moduleIntegrationTestRunner({
})
it("should allow for at most two tokens, where one is revoked", async function () {
const firstApiKey = await service.create(createSecretKeyFixture)
const firstApiKey = await service.createApiKeys(
createSecretKeyFixture
)
await service.revoke(
{ id: firstApiKey.id },
{
@@ -112,9 +116,9 @@ moduleIntegrationTestRunner({
}
)
await service.create(createSecretKeyFixture)
await service.createApiKeys(createSecretKeyFixture)
const err = await service
.create(createSecretKeyFixture)
.createApiKeys(createSecretKeyFixture)
.catch((e) => e)
expect(err.message).toEqual(
"You can only have one active secret key a time. Revoke or delete your existing key before creating a new one."
@@ -124,7 +128,9 @@ moduleIntegrationTestRunner({
describe("revoking API keys", () => {
it("should have the revoked at and revoked by set when a key is revoked", async function () {
const firstApiKey = await service.create(createSecretKeyFixture)
const firstApiKey = await service.createApiKeys(
createSecretKeyFixture
)
const revokedKey = await service.revoke(firstApiKey.id, {
revoked_by: "test",
})
@@ -142,7 +148,7 @@ moduleIntegrationTestRunner({
const hourInSec = 3600
jest.useFakeTimers().setSystemTime(now)
const createdKey = await service.create(createSecretKeyFixture)
const createdKey = await service.createApiKeys(createSecretKeyFixture)
const revokedKey = await service.revoke(createdKey.id, {
revoked_by: "test",
revoke_in: hourInSec,
@@ -159,17 +165,21 @@ moduleIntegrationTestRunner({
})
it("should do nothing if the revokal list is empty", async function () {
const firstApiKey = await service.create(createSecretKeyFixture)
const firstApiKey = await service.createApiKeys(
createSecretKeyFixture
)
let revokedKeys = await service.revoke([])
expect(revokedKeys).toHaveLength(0)
const apiKey = await service.retrieve(firstApiKey.id)
const apiKey = await service.retrieveApiKey(firstApiKey.id)
expect(apiKey.revoked_at).toBeFalsy()
expect(apiKey.revoked_by).toBeFalsy()
})
it("should not allow revoking an already revoked API key", async function () {
const firstApiKey = await service.create(createSecretKeyFixture)
const firstApiKey = await service.createApiKeys(
createSecretKeyFixture
)
await service.revoke(firstApiKey.id, {
revoked_by: "test",
})
@@ -188,18 +198,22 @@ moduleIntegrationTestRunner({
describe("updating an API key", () => {
it("should update the name successfully", async function () {
const createdApiKey = await service.create(createSecretKeyFixture)
const createdApiKey = await service.createApiKeys(
createSecretKeyFixture
)
const updatedApiKey = await service.update(createdApiKey.id, {
const updatedApiKey = await service.updateApiKeys(createdApiKey.id, {
title: "New Name",
})
expect(updatedApiKey.title).toEqual("New Name")
})
it("should not reflect any updates on other fields", async function () {
const createdApiKey = await service.create(createSecretKeyFixture)
const createdApiKey = await service.createApiKeys(
createSecretKeyFixture
)
const updatedApiKey = await service.update(createdApiKey.id, {
const updatedApiKey = await service.updateApiKeys(createdApiKey.id, {
title: createdApiKey.title,
revoked_by: "test",
revoked_at: new Date(),
@@ -214,27 +228,34 @@ moduleIntegrationTestRunner({
describe("deleting API keys", () => {
it("should successfully delete existing api keys", async function () {
const createdApiKeys = await service.create([
const createdApiKeys = await service.createApiKeys([
createPublishableKeyFixture,
createSecretKeyFixture,
])
await service.delete([createdApiKeys[0].id, createdApiKeys[1].id])
await service.deleteApiKeys([
createdApiKeys[0].id,
createdApiKeys[1].id,
])
const apiKeysInDatabase = await service.list()
const apiKeysInDatabase = await service.listApiKeys()
expect(apiKeysInDatabase).toHaveLength(0)
})
})
describe("authenticating with API keys", () => {
it("should authenticate a secret key successfully", async function () {
const createdApiKey = await service.create(createSecretKeyFixture)
const createdApiKey = await service.createApiKeys(
createSecretKeyFixture
)
const authenticated = await service.authenticate(createdApiKey.token)
expect(authenticated).toBeTruthy()
expect(authenticated.title).toEqual(createSecretKeyFixture.title)
})
it("should authenticate with a token to be revoked in the future", async function () {
const createdApiKey = await service.create(createSecretKeyFixture)
const createdApiKey = await service.createApiKeys(
createSecretKeyFixture
)
// We simulate setting the revoked_at in the future here
jest.useFakeTimers().setSystemTime(new Date().setFullYear(3000))
@@ -249,7 +270,7 @@ moduleIntegrationTestRunner({
})
it("should not authenticate a publishable key", async function () {
const createdApiKey = await service.create(
const createdApiKey = await service.createApiKeys(
createPublishableKeyFixture
)
const authenticated = await service.authenticate(createdApiKey.token)
@@ -257,13 +278,17 @@ moduleIntegrationTestRunner({
expect(authenticated).toBeFalsy()
})
it("should not authenticate with a non-existent token", async function () {
const createdApiKey = await service.create(createSecretKeyFixture)
const createdApiKey = await service.createApiKeys(
createSecretKeyFixture
)
const authenticated = await service.authenticate("some-token")
expect(authenticated).toBeFalsy()
})
it("should not authenticate with a revoked token", async function () {
const createdApiKey = await service.create(createSecretKeyFixture)
const createdApiKey = await service.createApiKeys(
createSecretKeyFixture
)
await service.revoke(createdApiKey.id, {
revoked_by: "test",
})
@@ -275,22 +300,22 @@ moduleIntegrationTestRunner({
describe("retrieving API keys", () => {
it("should successfully return all existing api keys", async function () {
await service.create([
await service.createApiKeys([
createPublishableKeyFixture,
createSecretKeyFixture,
])
const apiKeysInDatabase = await service.list()
const apiKeysInDatabase = await service.listApiKeys()
expect(apiKeysInDatabase).toHaveLength(2)
})
it("should only return keys with matching token", async function () {
const created = await service.create([
const created = await service.createApiKeys([
createPublishableKeyFixture,
createPublishableKeyFixture,
])
const apiKeysInDatabase = await service.list({
const apiKeysInDatabase = await service.listApiKeys({
token: created[0].token,
})
expect(apiKeysInDatabase).toHaveLength(1)
@@ -298,55 +323,61 @@ moduleIntegrationTestRunner({
})
it("should not return the token and salt for secret keys when listing", async function () {
await service.create([createSecretKeyFixture])
await service.createApiKeys([createSecretKeyFixture])
const apiKeysInDatabase = await service.list()
const apiKeysInDatabase = await service.listApiKeys()
expect(apiKeysInDatabase).toHaveLength(1)
expect(apiKeysInDatabase[0].token).toBeFalsy()
expect(apiKeysInDatabase[0].salt).toBeFalsy()
})
it("should return the token for publishable keys when listing", async function () {
await service.create([createPublishableKeyFixture])
await service.createApiKeys([createPublishableKeyFixture])
const apiKeysInDatabase = await service.list()
const apiKeysInDatabase = await service.listApiKeys()
expect(apiKeysInDatabase).toHaveLength(1)
expect(apiKeysInDatabase[0].token).toBeTruthy()
expect(apiKeysInDatabase[0].salt).toBeFalsy()
})
it("should not return the token and salt for secret keys when listing and counting", async function () {
await service.create([createSecretKeyFixture])
await service.createApiKeys([createSecretKeyFixture])
const [apiKeysInDatabase] = await service.listAndCount()
const [apiKeysInDatabase] = await service.listAndCountApiKeys()
expect(apiKeysInDatabase).toHaveLength(1)
expect(apiKeysInDatabase[0].token).toBeFalsy()
expect(apiKeysInDatabase[0].salt).toBeFalsy()
})
it("should return the token for publishable keys when listing and counting", async function () {
await service.create([createPublishableKeyFixture])
await service.createApiKeys([createPublishableKeyFixture])
const [apiKeysInDatabase] = await service.listAndCount()
const [apiKeysInDatabase] = await service.listAndCountApiKeys()
expect(apiKeysInDatabase).toHaveLength(1)
expect(apiKeysInDatabase[0].token).toBeTruthy()
expect(apiKeysInDatabase[0].salt).toBeFalsy()
})
it("should not return the token and salt for secret keys when retrieving", async function () {
const [createdApiKey] = await service.create([createSecretKeyFixture])
const [createdApiKey] = await service.createApiKeys([
createSecretKeyFixture,
])
const apiKeyInDatabase = await service.retrieve(createdApiKey.id)
const apiKeyInDatabase = await service.retrieveApiKey(
createdApiKey.id
)
expect(apiKeyInDatabase.token).toBeFalsy()
expect(apiKeyInDatabase.salt).toBeFalsy()
})
it("should return the token for publishable keys when retrieving", async function () {
const [createdApiKey] = await service.create([
const [createdApiKey] = await service.createApiKeys([
createPublishableKeyFixture,
])
const apiKeyInDatabase = await service.retrieve(createdApiKey.id)
const apiKeyInDatabase = await service.retrieveApiKey(
createdApiKey.id
)
expect(apiKeyInDatabase.token).toBeTruthy()
expect(apiKeyInDatabase.salt).toBeFalsy()
})

View File

@@ -8,10 +8,7 @@
"dist"
],
"engines": {
"node": ">=16"
},
"bin": {
"medusa-api-key-seed": "dist/scripts/bin/run-seed.js"
"node": ">=20"
},
"repository": {
"type": "git",

View File

@@ -1,7 +1,5 @@
import { moduleDefinition } from "./module-definition"
export * from "./types"
export * from "./models"
export * from "./services"
import { ModuleExports } from "@medusajs/types"
import { ApiKeyModuleService } from "@services"
const moduleDefinition: ModuleExports = { service: ApiKeyModuleService }
export default moduleDefinition

View File

@@ -1,31 +1,11 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import ApiKey from "./models/api-key"
import {
buildEntitiesNameToLinkableKeysMap,
defineJoinerConfig,
MapToConfig,
} from "@medusajs/utils"
export const LinkableKeys: Record<string, string> = {
api_key_id: ApiKey.name,
}
export const joinerConfig = defineJoinerConfig(Modules.API_KEY)
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.API_KEY,
primaryKeys: ["id"],
linkableKeys: LinkableKeys,
alias: [
{
name: ["api_key", "api_keys"],
args: { entity: ApiKey.name },
},
],
} as ModuleJoinerConfig
export const entityNameToLinkableKeysMap: MapToConfig =
buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys)

View File

@@ -1,8 +0,0 @@
import { ModuleExports } from "@medusajs/types"
import { ApiKeyModuleService } from "@services"
const service = ApiKeyModuleService
export const moduleDefinition: ModuleExports = {
service,
}

View File

@@ -1 +0,0 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"

View File

@@ -1,29 +0,0 @@
#!/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-api-key-seed <filePath>`
)
}
const run = ModulesSdkUtils.buildSeedScript({
moduleName: Modules.API_KEY,
models: Models,
pathToMigrations: __dirname + "/../../migrations",
seedHandler: async ({ manager, data }) => {
// TODO: Add seed logic
},
})
await run({ path })
})()

View File

@@ -27,7 +27,7 @@ import {
isString,
MedusaContext,
MedusaError,
ModulesSdkUtils,
MedusaService,
promiseAll,
} from "@medusajs/utils"
@@ -38,17 +38,14 @@ type InjectedDependencies = {
apiKeyService: ModulesSdkTypes.IMedusaInternalService<any>
}
export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
extends ModulesSdkUtils.MedusaService<
ApiKeyTypes.ApiKeyDTO,
{
ApiKey: { dto: ApiKeyTypes.ApiKeyDTO }
}
>(ApiKey, {}, entityNameToLinkableKeysMap)
export default class ApiKeyModuleService
extends MedusaService<{
ApiKey: { dto: ApiKeyTypes.ApiKeyDTO }
}>({ ApiKey }, entityNameToLinkableKeysMap)
implements IApiKeyModuleService
{
protected baseRepository_: DAL.RepositoryService
protected readonly apiKeyService_: ModulesSdkTypes.IMedusaInternalService<TEntity>
protected readonly apiKeyService_: ModulesSdkTypes.IMedusaInternalService<ApiKey>
constructor(
{ baseRepository, apiKeyService }: InjectedDependencies,
@@ -63,22 +60,22 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
__joinerConfig(): ModuleJoinerConfig {
return joinerConfig
}
create(
//@ts-expect-error
createApiKeys(
data: ApiKeyTypes.CreateApiKeyDTO[],
sharedContext?: Context
): Promise<ApiKeyTypes.ApiKeyDTO[]>
create(
createApiKeys(
data: ApiKeyTypes.CreateApiKeyDTO,
sharedContext?: Context
): Promise<ApiKeyTypes.ApiKeyDTO>
@InjectManager("baseRepository_")
async create(
async createApiKeys(
data: ApiKeyTypes.CreateApiKeyDTO | ApiKeyTypes.CreateApiKeyDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<ApiKeyTypes.ApiKeyDTO | ApiKeyTypes.ApiKeyDTO[]> {
const [createdApiKeys, generatedTokens] = await this.create_(
const [createdApiKeys, generatedTokens] = await this.createApiKeys_(
Array.isArray(data) ? data : [data],
sharedContext
)
@@ -102,10 +99,10 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
}
@InjectTransactionManager("baseRepository_")
protected async create_(
protected async createApiKeys_(
data: ApiKeyTypes.CreateApiKeyDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<[TEntity[], TokenDTO[]]> {
): Promise<[ApiKey[], TokenDTO[]]> {
await this.validateCreateApiKeys_(data, sharedContext)
const normalizedInput: CreateApiKeyDTO[] = []
@@ -135,17 +132,17 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
return [createdApiKeys, generatedTokens]
}
async upsert(
async upsertApiKeys(
data: ApiKeyTypes.UpsertApiKeyDTO[],
sharedContext?: Context
): Promise<ApiKeyTypes.ApiKeyDTO[]>
async upsert(
async upsertApiKeys(
data: ApiKeyTypes.UpsertApiKeyDTO,
sharedContext?: Context
): Promise<ApiKeyTypes.ApiKeyDTO>
@InjectManager("baseRepository_")
async upsert(
async upsertApiKeys(
data: ApiKeyTypes.UpsertApiKeyDTO | ApiKeyTypes.UpsertApiKeyDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<ApiKeyTypes.ApiKeyDTO | ApiKeyTypes.ApiKeyDTO[]> {
@@ -161,7 +158,7 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
if (forCreate.length) {
const op = async () => {
const [createdApiKeys, generatedTokens] = await this.create_(
const [createdApiKeys, generatedTokens] = await this.createApiKeys_(
forCreate,
sharedContext
)
@@ -188,7 +185,7 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
if (forUpdate.length) {
const op = async () => {
const updateResp = await this.update_(forUpdate, sharedContext)
const updateResp = await this.updateApiKeys_(forUpdate, sharedContext)
return await this.baseRepository_.serialize<ApiKeyTypes.ApiKeyDTO[]>(
updateResp
)
@@ -201,19 +198,20 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
return Array.isArray(data) ? result : result[0]
}
async update(
//@ts-expect-error
async updateApiKeys(
id: string,
data: ApiKeyTypes.UpdateApiKeyDTO,
sharedContext?: Context
): Promise<ApiKeyTypes.ApiKeyDTO>
async update(
async updateApiKeys(
selector: FilterableApiKeyProps,
data: ApiKeyTypes.UpdateApiKeyDTO,
sharedContext?: Context
): Promise<ApiKeyTypes.ApiKeyDTO[]>
@InjectManager("baseRepository_")
async update(
async updateApiKeys(
idOrSelector: string | FilterableApiKeyProps,
data: ApiKeyTypes.UpdateApiKeyDTO,
@MedusaContext() sharedContext: Context = {}
@@ -224,7 +222,10 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
sharedContext
)
const updatedApiKeys = await this.update_(normalizedInput, sharedContext)
const updatedApiKeys = await this.updateApiKeys_(
normalizedInput,
sharedContext
)
const serializedResponse = await this.baseRepository_.serialize<
ApiKeyTypes.ApiKeyDTO[]
@@ -236,10 +237,10 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
}
@InjectTransactionManager("baseRepository_")
protected async update_(
protected async updateApiKeys_(
normalizedInput: UpdateApiKeyInput[],
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity[]> {
): Promise<ApiKey[]> {
const updateRequest = normalizedInput.map((k) => ({
id: k.id,
title: k.title,
@@ -253,7 +254,8 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
}
@InjectManager("baseRepository_")
async retrieve(
// @ts-expect-error
async retrieveApiKey(
id: string,
config?: FindConfig<ApiKeyTypes.ApiKeyDTO>,
sharedContext?: Context
@@ -269,7 +271,8 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
}
@InjectManager("baseRepository_")
async list(
//@ts-expect-error
async listApiKeys(
filters?: ApiKeyTypes.FilterableApiKeyProps,
config?: FindConfig<ApiKeyTypes.ApiKeyDTO>,
sharedContext?: Context
@@ -289,7 +292,8 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
}
@InjectManager("baseRepository_")
async listAndCount(
//@ts-expect-error
async listAndCountApiKeys(
filters?: ApiKeyTypes.FilterableApiKeyProps,
config?: FindConfig<ApiKeyTypes.ApiKeyDTO>,
sharedContext?: Context
@@ -347,7 +351,7 @@ export default class ApiKeyModuleService<TEntity extends ApiKey = ApiKey>
async revoke_(
normalizedInput: RevokeApiKeyInput[],
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity[]> {
): Promise<ApiKey[]> {
await this.validateRevokeApiKeys_(normalizedInput)
const updateRequest = normalizedInput.map((k) => {