chore: move ModuleRegistrationName to utils (#7911)

This commit is contained in:
Carlos R. L. Rodrigues
2024-07-03 06:30:56 -03:00
committed by GitHub
parent 46f15b4909
commit a7844efd09
339 changed files with 7203 additions and 7620 deletions
@@ -30,15 +30,9 @@ To disable the authentication guard on custom routes under the `/admin` or `/sto
For example:
```ts title="src/api/store/customers/me/custom/route.ts" highlights={[["15"]]} apiTesting testApiUrl="http://localhost:9000/store/customers/me/custom" testApiMethod="GET"
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/medusa"
import type { MedusaRequest, MedusaResponse } from "@medusajs/medusa"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
res.json({
message: "Hello",
})
@@ -62,15 +56,16 @@ import type {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/medusa"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { ModuleRegistrationName } from "@medusajs/utils"
import { ICustomerModuleService } from "@medusajs/types"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
const customerModuleService: ICustomerModuleService =
req.scope.resolve(ModuleRegistrationName.CUSTOMER)
const customerModuleService: ICustomerModuleService = req.scope.resolve(
ModuleRegistrationName.CUSTOMER
)
const customer = await customerModuleService.retrieve(
req.auth_context.actor_id
@@ -95,7 +90,7 @@ import type {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/medusa"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { ModuleRegistrationName } from "@medusajs/utils"
import { IUserModuleService } from "@medusajs/types"
export const GET = async (
@@ -106,9 +101,7 @@ export const GET = async (
ModuleRegistrationName.USER
)
const user = await userService.retrieve(
req.auth_context.actor_id
)
const user = await userService.retrieve(req.auth_context.actor_id)
// ...
}
@@ -125,29 +118,30 @@ To protect custom API Routes that dont start with `/store/customers/me` or `/
For example:
export const highlights = [
["11", "authenticate", "Only authenticated admin users can access routes starting with `/custom/admin`"],
["17", "authenticate", "Only authenticated customers can access routes starting with `/custom/customers`"]
[
"11",
"authenticate",
"Only authenticated admin users can access routes starting with `/custom/admin`",
],
[
"17",
"authenticate",
"Only authenticated customers can access routes starting with `/custom/customers`",
],
]
```ts title="src/api/middlewares.ts" highlights={highlights}
import {
MiddlewaresConfig,
authenticate,
} from "@medusajs/medusa"
import { MiddlewaresConfig, authenticate } from "@medusajs/medusa"
export const config: MiddlewaresConfig = {
routes: [
{
matcher: "/custom/admin*",
middlewares: [
authenticate("user", ["session", "bearer", "api-key"]),
],
middlewares: [authenticate("user", ["session", "bearer", "api-key"])],
},
{
matcher: "/custom/customer*",
middlewares: [
authenticate("customer", ["session", "bearer"]),
],
middlewares: [authenticate("customer", ["session", "bearer"])],
},
],
}
@@ -158,5 +152,5 @@ The `authenticate` middleware function accepts three parameters:
1. The type of user authenticating. Use `user` for authenticating admin users, and `customer` for authenticating customers.
2. An array of the types of authentication methods allowed. Both `user` and `customer` scopes support `session` and `bearer`. The `admin` scope also supports the `api-key` authentication method.
3. An optional object of options having the following properties:
1. `allowUnauthenticated`: (default: `false`) A boolean indicating whether authentication is required. For example, you may have an API route where you want to access the logged-in customer if available, but guest customers can still access it too. In that case, enable the `allowUnauthenticated` option.
2. `allowUnregistered`: (default: `false`) A boolean indicating whether new users can be authenticated.
1. `allowUnauthenticated`: (default: `false`) A boolean indicating whether authentication is required. For example, you may have an API route where you want to access the logged-in customer if available, but guest customers can still access it too. In that case, enable the `allowUnauthenticated` option.
2. `allowUnregistered`: (default: `false`) A boolean indicating whether new users can be authenticated.
@@ -19,17 +19,13 @@ To create a custom CLI script, create a TypeScript or JavaScript file under the
For example, create the file `src/scripts/my-script.ts` with the following content:
```ts title="src/scripts/my-script.ts"
import {
ExecArgs,
IProductModuleService,
} from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { ExecArgs, IProductModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/utils"
export default async function myScript({
container,
}: ExecArgs) {
const productModuleService: IProductModuleService =
container.resolve(ModuleRegistrationName.PRODUCT)
export default async function myScript({ container }: ExecArgs) {
const productModuleService: IProductModuleService = container.resolve(
ModuleRegistrationName.PRODUCT
)
const [, count] = await productModuleService.listAndCount()
@@ -60,9 +56,7 @@ For example:
```ts
import { ExecArgs } from "@medusajs/types"
export default async function myScript({
args,
}: ExecArgs) {
export default async function myScript({ args }: ExecArgs) {
console.log(`The arguments you passed: ${args}`)
}
```
@@ -22,9 +22,7 @@ For example, create the file `src/loaders/hello-world.ts` with the following con
```ts title="src/loaders/hello-world.ts"
export default function () {
console.log(
"[HELLO LOADER] Just started the Medusa application!"
)
console.log("[HELLO LOADER] Just started the Medusa application!")
}
```
@@ -51,11 +49,12 @@ For example:
```ts title="src/loaders/hello-world.ts" collapsibleLines="1-5" expandButtonLabel="Show Imports"
import { MedusaContainer } from "@medusajs/medusa"
import { IProductModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { ModuleRegistrationName } from "@medusajs/utils"
export default async function (container: MedusaContainer) {
const productModuleService: IProductModuleService =
container.resolve(ModuleRegistrationName.PRODUCT)
const productModuleService: IProductModuleService = container.resolve(
ModuleRegistrationName.PRODUCT
)
const [, count] = await productModuleService.listAndCount()
@@ -78,13 +77,11 @@ import { MedusaContainer } from "@medusajs/medusa"
import { ConfigModule } from "@medusajs/types"
export default async function (
container: MedusaContainer,
container: MedusaContainer,
config: ConfigModule
) {
console.log(`You have ${
Object.values(config.modules || {}).length
} modules!`)
console.log(`You have ${Object.values(config.modules || {}).length} modules!`)
}
```
This loader logs on application start-up the number of modules defined in your Medusa configurations.
This loader logs on application start-up the number of modules defined in your Medusa configurations.
@@ -26,7 +26,6 @@ In the file, add the type of the expected workflow input:
import { UpdateProductDTO } from "@medusajs/types"
export type UpdateProductAndErpWorkflowInput = UpdateProductDTO
```
The expected input is the data to update in the product along with the products ID.
@@ -41,18 +40,23 @@ Create the file `src/workflows/update-product-erp/steps/update-product.ts` with
export const updateProductHighlights = [
["13", "resolve", "Resolve the `ProductService` from the Medusa container."],
["16", "previousProductData", "Retrieve the `previousProductData` to pass it to the compensation function."],
[
"16",
"previousProductData",
"Retrieve the `previousProductData` to pass it to the compensation function.",
],
["19", "", "Update the product."],
["39", "", "Revert the products data using the `previousProductData` passed from the step to the compensation function."]
[
"39",
"",
"Revert the products data using the `previousProductData` passed from the step to the compensation function.",
],
]
```ts title="src/workflows/update-product-erp/steps/update-product.ts" highlights={updateProductHighlights} collapsibleLines="1-9" expandButtonLabel="Show Imports"
import {
createStep,
StepResponse,
} from "@medusajs/workflows-sdk"
import { createStep, StepResponse } from "@medusajs/workflows-sdk"
import { IProductModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { ModuleRegistrationName } from "@medusajs/utils"
import { UpdateProductAndErpWorkflowInput } from ".."
const updateProduct = createStep(
@@ -62,8 +66,7 @@ const updateProduct = createStep(
context.container.resolve(ModuleRegistrationName.PRODUCT)
const { id } = input
const previousProductData =
await productModuleService.retrieve(id)
const previousProductData = await productModuleService.retrieve(id)
const product = await productModuleService.update(id, input)
@@ -77,37 +80,28 @@ const updateProduct = createStep(
const productModuleService: IProductModuleService =
context.container.resolve(ModuleRegistrationName.PRODUCT)
const {
id,
type,
options,
variants,
...previousData
} = previousProductData
const { id, type, options, variants, ...previousData } = previousProductData
await productModuleService.update(
id,
{
...previousData,
variants: variants.map((variant) => {
const variantOptions = {}
await productModuleService.update(id, {
...previousData,
variants: variants.map((variant) => {
const variantOptions = {}
variant.options.forEach((option) => {
variantOptions[option.option.title] = option.value
})
variant.options.forEach((option) => {
variantOptions[option.option.title] = option.value
})
return {
...variant,
options: variantOptions,
}
}),
options: options.map((option) => ({
...option,
values: option.values.map((value) => value.value),
})),
type_id: type.id,
}
)
return {
...variant,
options: variantOptions,
}
}),
options: options.map((option) => ({
...option,
values: option.values.map((value) => value.value),
})),
type_id: type.id,
})
}
)
@@ -139,17 +133,30 @@ The `ErpModuleService` used is assumed to be created in a module.
Create the file `src/workflows/update-product-erp/steps/update-erp.ts` with the following content:
export const updateErpHighlights = [
["12", "resolve", "Resolve the `erpModuleService` from the Medusa container."],
["17", "previousErpData", "Retrieve the `previousErpData` to pass it to the compensation function."],
["21", "updateProductErpData", "Update the products ERP data and return the data from the ERP system."],
["37", "updateProductErpData", "Revert the product's data in the ERP system to its previous state using the `previousErpData`."]
[
"12",
"resolve",
"Resolve the `erpModuleService` from the Medusa container.",
],
[
"17",
"previousErpData",
"Retrieve the `previousErpData` to pass it to the compensation function.",
],
[
"21",
"updateProductErpData",
"Update the products ERP data and return the data from the ERP system.",
],
[
"37",
"updateProductErpData",
"Revert the product's data in the ERP system to its previous state using the `previousErpData`.",
],
]
```ts title="src/workflows/update-product-erp/steps/update-erp.ts" highlights={updateErpHighlights} collapsibleLines="1-8" expandButtonLabel="Show Imports"
import {
createStep,
StepResponse,
} from "@medusajs/workflows-sdk"
import { createStep, StepResponse } from "@medusajs/workflows-sdk"
import { UpdateProductAndErpWorkflowInput } from ".."
import ErpModuleService from "../../../modules/erp/service"
@@ -162,14 +169,12 @@ const updateErp = createStep(
const { id, ...updatedData } = input
// get previous ERP data
const previousErpData =
await erpModuleService.retrieveProductErpDetails(id)
const previousErpData = await erpModuleService.retrieveProductErpDetails(id)
const updatedErpData =
await erpModuleService.updateProductErpData(
id,
updatedData
)
const updatedErpData = await erpModuleService.updateProductErpData(
id,
updatedData
)
return new StepResponse(updatedErpData, {
// pass to compensation function
@@ -179,13 +184,9 @@ const updateErp = createStep(
},
// compensation function
async ({ previousErpData, productId }, context) => {
const erpService: ErpModuleService =
context.container.resolve("erpService")
const erpService: ErpModuleService = context.container.resolve("erpService")
await erpService.updateProductErpData(
productId,
previousErpData
)
await erpService.updateProductErpData(productId, previousErpData)
}
)
@@ -253,10 +254,7 @@ import updateProductAndErpWorkflow, {
UpdateProductAndErpWorkflowInput,
} from "../../../../../workflows/update-product-erp"
type ProductErpReq = Omit<
UpdateProductAndErpWorkflowInput,
"id"
>
type ProductErpReq = Omit<UpdateProductAndErpWorkflowInput, "id">
export const POST = async (
req: MedusaRequest<ProductErpReq>,
@@ -268,9 +266,7 @@ export const POST = async (
...req.body,
}
const { result } = await updateProductAndErpWorkflow(
req.scope
).run({
const { result } = await updateProductAndErpWorkflow(req.scope).run({
input: productData,
})
@@ -280,4 +276,4 @@ export const POST = async (
In this `POST` API route, you retrieve the products ID from the path parameter and the data to update from the request body. You then execute the workflow by passing it the retrieved data as an input.
The route returns the result of the workflow, which is an object holding both the update products details and the ERP details.
The route returns the result of the workflow, which is an object holding both the update products details and the ERP details.
@@ -23,10 +23,7 @@ A workflow is considered long-running if at least one step has its `async` confi
For example, consider the following workflow and steps:
```ts title="src/workflows/hello-world.ts" highlights={[["13"]]} collapsibleLines="1-10" expandButtonLabel="Show More"
import {
createStep,
createWorkflow,
} from "@medusajs/workflows-sdk"
import { createStep, createWorkflow } from "@medusajs/workflows-sdk"
const step1 = createStep("step-1", async () => {
// ...
@@ -50,19 +47,18 @@ type WorkflowOutput = {
message: string
}
const myWorkflow = createWorkflow<
{},
WorkflowOutput
>({
name: "hello-world",
}, function () {
step1()
step2()
step3()
})
const myWorkflow = createWorkflow<{}, WorkflowOutput>(
{
name: "hello-world",
},
function () {
step1()
step2()
step3()
}
)
export default myWorkflow
```
The second step has in its configuration object `async` set to true. This indicates that this step is an asynchronous step.
@@ -89,26 +85,15 @@ export const highlights = [
]
```ts title="src/api/store/workflows/route.ts" highlights={highlights} collapsibleLines="1-11" expandButtonLabel="Show Imports"
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/medusa"
import type { MedusaRequest, MedusaResponse } from "@medusajs/medusa"
import myWorkflow from "../../../workflows/hello-world"
import {
IWorkflowEngineService,
} from "@medusajs/workflows-sdk"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IWorkflowEngineService } from "@medusajs/workflows-sdk"
import { ModuleRegistrationName } from "@medusajs/utils"
export async function GET(
req: MedusaRequest,
res: MedusaResponse
) {
const { transaction, result } = await myWorkflow(req.scope)
.run()
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const { transaction, result } = await myWorkflow(req.scope).run()
const workflowEngine = req.scope.resolve<
IWorkflowEngineService
>(
const workflowEngine = req.scope.resolve<IWorkflowEngineService>(
ModuleRegistrationName.WORKFLOW_ENGINE
)
@@ -137,18 +122,20 @@ The `subscribe` method accepts an object having three properties:
{
name: "workflowId",
type: "`string`",
description: "The name of the workflow."
description: "The name of the workflow.",
},
{
name: "transactionId",
type: "`string`",
description: "The ID of the workflow exection's transaction. The transaction's details are returned in the response of the workflow execution."
description:
"The ID of the workflow exection's transaction. The transaction's details are returned in the response of the workflow execution.",
},
{
name: "subscriber",
type: "`string`",
description: "The function executed when the workflow execution's status changes. The function receives a data object. It has an `eventType` property, which you use to check the status of the workflow execution."
}
description:
"The function executed when the workflow execution's status changes. The function receives a data object. It has an `eventType` property, which you use to check the status of the workflow execution.",
},
]}
sectionTitle="Access Long-Running Workflow Status and Result"
/>