docs: add section on validating module options (#11427)

This commit is contained in:
Shahed Nasser
2025-02-12 18:25:15 +02:00
committed by GitHub
parent 00fa475e77
commit d9946e679d
3 changed files with 13072 additions and 12982 deletions

View File

@@ -118,3 +118,48 @@ export default async function helloWorldLoader({
)
}
```
---
## Validate Module Options
If you expect a certain option and want to throw an error if it's not provided or isn't valid, it's recommended to perform the validation in a loader. The module's service is only instantiated when it's used, whereas the loader runs the when the Medusa application starts.
So, by performing the validation in the loader, you ensure you can throw an error at an early point, rather than when the module is used.
For example, to validate that the Hello Module received an `apiKey` option, create the loader `src/modules/loaders/validate.ts`:
```ts title="src/modules/hello/loaders/validate.ts"
import { LoaderOptions } from "@medusajs/framework/types"
import { MedusaError } from "@medusajs/framework/utils"
// recommended to define type in another file
type ModuleOptions = {
apiKey?: string
}
export default async function validationLoader({
options,
}: LoaderOptions<ModuleOptions>) {
if (!options.apiKey) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Hello Module requires an apiKey option."
)
}
}
```
Then, export the loader in the module's definition file, as explained in [this chapter](../loaders/page.mdx):
```ts title="src/modules/hello/index.ts"
// other imports...
import validationLoader from "./loaders/validate"
export default Module("hello", {
// ...
loaders: [validationLoader],
})
```
Now, when the Medusa application starts, the loader will run, validating the module's options and throwing an error if the `apiKey` option is missing.

View File

@@ -40,7 +40,7 @@ export const generatedEditDates = {
"app/learn/fundamentals/data-models/write-migration/page.mdx": "2024-11-11T15:27:59.794Z",
"app/learn/fundamentals/data-models/manage-relationships/page.mdx": "2025-02-11T15:53:12.541Z",
"app/learn/fundamentals/modules/remote-query/page.mdx": "2024-07-21T21:20:24+02:00",
"app/learn/fundamentals/modules/options/page.mdx": "2025-01-16T09:21:38.244Z",
"app/learn/fundamentals/modules/options/page.mdx": "2025-02-12T16:00:28.484Z",
"app/learn/fundamentals/data-models/relationships/page.mdx": "2025-02-03T08:01:18.094Z",
"app/learn/fundamentals/workflows/compensation-function/page.mdx": "2024-12-06T14:34:50.384Z",
"app/learn/fundamentals/modules/service-factory/page.mdx": "2024-10-21T13:30:21.371Z",

File diff suppressed because it is too large Load Diff