Files
medusa-store/www/docs/content/development/modules/create.mdx
Shahed Nasser 914d773d3a api-ref: custom API reference (#4770)
* initialized next.js project

* finished markdown sections

* added operation schema component

* change page metadata

* eslint fixes

* fixes related to deployment

* added response schema

* resolve max stack issue

* support for different property types

* added support for property types

* added loading for components

* added more loading

* type fixes

* added oneOf type

* removed console

* fix replace with push

* refactored everything

* use static content for description

* fixes and improvements

* added code examples section

* fix path name

* optimizations

* fixed tag navigation

* add support for admin and store references

* general enhancements

* optimizations and fixes

* fixes and enhancements

* added search bar

* loading enhancements

* added loading

* added code blocks

* added margin top

* add empty response text

* fixed oneOf parameters

* added path and query parameters

* general fixes

* added base path env variable

* small fix for arrays

* enhancements

* design enhancements

* general enhancements

* fix isRequired

* added enum values

* enhancements

* general fixes

* general fixes

* changed oas generation script

* additions to the introduction section

* added copy button for code + other enhancements

* fix response code block

* fix metadata

* formatted store introduction

* move sidebar logic to Tags component

* added test env variables

* fix code block bug

* added loading animation

* added expand param + loading

* enhance operation loading

* made responsive + improvements

* added loading provider

* fixed loading

* adjustments for small devices

* added sidebar label for endpoints

* added feedback component

* fixed analytics

* general fixes

* listen to scroll for other headings

* added sample env file

* update api ref files + support new fields

* fix for external docs link

* added new sections

* fix last item in sidebar not showing

* move docs content to www/docs

* change redirect url

* revert change

* resolve build errors

* configure rewrites

* changed to environment variable url

* revert changing environment variable name

* add environment variable for API path

* fix links

* fix tailwind settings

* remove vercel file

* reconfigured api route

* move api page under api

* fix page metadata

* fix external link in navigation bar

* update api spec

* updated api specs

* fixed google lint error

* add max-height on request samples

* add padding before loading

* fix for one of name

* fix undefined types

* general fixes

* remove response schema example

* redesigned navigation bar

* redesigned sidebar

* fixed up paddings

* added feedback component + report issue

* fixed up typography, padding, and general styling

* redesigned code blocks

* optimization

* added error timeout

* fixes

* added indexing with algolia + fixes

* fix errors with algolia script

* redesign operation sections

* fix heading scroll

* design fixes

* fix padding

* fix padding + scroll issues

* fix scroll issues

* improve scroll performance

* fixes for safari

* optimization and fixes

* fixes to docs + details animation

* padding fixes for code block

* added tab animation

* fixed incorrect link

* added selection styling

* fix lint errors

* redesigned details component

* added detailed feedback form

* api reference fixes

* fix tabs

* upgrade + fixes

* updated documentation links

* optimizations to sidebar items

* fix spacing in sidebar item

* optimizations and fixes

* fix endpoint path styling

* remove margin

* final fixes

* change margin on small devices

* generated OAS

* fixes for mobile

* added feedback modal

* optimize dark mode button

* fixed color mode useeffect

* minimize dom size

* use new style system

* radius and spacing design system

* design fixes

* fix eslint errors

* added meta files

* change cron schedule

* fix docusaurus configurations

* added operating system to feedback data

* change content directory name

* fixes to contribution guidelines

* revert renaming content

* added api-reference to documentation workflow

* fixes for search

* added dark mode + fixes

* oas fixes

* handle bugs

* added code examples for clients

* changed tooltip text

* change authentication to card

* change page title based on selected section

* redesigned mobile navbar

* fix icon colors

* fix key colors

* fix medusa-js installation command

* change external regex in algolia

* change changeset

* fix padding on mobile

* fix hydration error

* update depedencies
2023-08-15 18:07:54 +03:00

310 lines
10 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
description: 'Learn how to create a module and test the module in your Medusa backend.'
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# How to Create a Module
In this document, youll learn how to create a module and test the module in your Medusa backend.
This document covers the general steps of creating an internal module, but does not explore actually implementing any functionality in it. An internal module is a TypeScript/JavaScript module that is loaded by the Medusa backend as part of the commerce application to extend or replace a functionality within it, such as the cache or event bus functionality.
---
## (Optional) Step 0: Project Preparation
Before you start implementing the custom functionality in your module, it's recommended to create a directory that holds your module and prepare the following structure in it:
```
custom-module
|
|___ src
|
|___ index.ts
|
|___ services // directory
```
The directory can be an NPM project, but that is optional. `index.ts` acts as an entry point to your Module. You'll learn about its content in a later step. The `service` directory will hold your custom services. If you're adding other resources you can add other directories for them. For example, if you're adding an entity you can add a `models` directory.
:::tip
You can use JavaScript instead of TypeScript.
:::
It's also recommended to use the following TypeScript config in `tsconfig.json`, which should be added in the root of the project holding your module:
```json
{
"compilerOptions": {
"lib": [
"es2020"
],
"target": "2020",
"outDir": "./dist",
"esModuleInterop": true,
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"noImplicitReturns": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"allowJs": true,
"skipLibCheck": true,
},
"include": ["src"],
"exclude": [
"dist",
"./src/**/__tests__",
"./src/**/__mocks__",
"./src/**/__fixtures__",
"node_modules"
]
}
```
---
## Step 1: Implement the Custom Functionality
This step depends on what youre actually implementing. For example, you can implement the cache or events module, or you can implement a commerce module. If what youre creating has a guide, you can refer to it while implementing the functionalities.
### Note About Project Structure
When developing your module, it's important to note that you'll later be referencing the module using a file path to an `index.ts` or `index.js` file. This file is explained in the next step and acts as an entry point and a definition of your module.
So, make sure when implementing your module you take into account that the module should be easily referenced from your local Medusa server. For example, you can develop your module in a sibling directory of the Medusa backend that you can reference with `../custom-module`.
Keep in mind that when you publish the module to NPM, you'll have to move your module into a new NPM project. This is covered in the [Publish Module documentation](./publish.md).
### Recommended Guides
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/cache/create',
label: 'Create a Cache Module',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a cache module in Medusa.',
}
},
{
type: 'link',
href: '/development/events/create-module',
label: 'Create an Events Module',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create an events module in Medusa.',
}
},
]} />
---
### Step 2: Export Module
After implementing the module, you must export a module object that helps the Medusa backend understand how to use this Module. This is done in the file `index.ts`.
The file must export an object with the following properties:
```ts
type ModuleExports = {
service: Constructor<any>
loaders?: ModuleLoaderFunction[]
migrations?: any[]
models?: Constructor<any>[]
runMigrations?(
options: LoaderOptions,
moduleDeclaration: InternalModuleDeclaration
): Promise<void>
revertMigration?(
options: LoaderOptions,
moduleDeclaration: InternalModuleDeclaration
): Promise<void>
}
```
:::tip
All property types such as `ModuleLoaderFunction` can be loaded from the `@medusajs/modules-sdk` package.
:::
Where:
- `service`: This is the only required property to be exported. It should be the main service your module exposes, and it must implement all the declared methods on the module interface. For example, if it's a cache module, it must implement the `ICacheService` interface exported from `@medusajs/types`.
- `loaders`: (optional) an array of [loader](../loaders/overview.mdx) functions used to perform an action while loading the module. For example, you can log a message that the module has been loaded, or if your module's scope is [isolated](#module-scope) you can use the loader to establish a database connection.
- `migrations`: (optional) an array of objects containing database migrations that should run when the `migration` command is used with Medusa's CLI.
- `models`: (optional) an array of entities that your module creates.
- `runMigrations`: (optional) a function that can be used to define migrations to run when the `migration run` command is used with Medusa's CLI. The migrations will only run if they haven't already. This will only be executed if the module's scope is [isolated](#module-scope).
- `revertMigration`: (optional) a function can be used to define how migrations should be reverted when the `migration revert` command is used with Medusa's CLI. This will only be executed if the module's scope is [isolated](#module-scope).
Here's an example implementation of `index.ts` from Medusa's Redis Cache module:
```ts title=index.ts
import { ModuleExports } from "@medusajs/modules-sdk"
import Loader from "./loaders"
import { RedisCacheService } from "./services"
const service = RedisCacheService
const loaders = [Loader]
const moduleDefinition: ModuleExports = {
service,
loaders,
}
export default moduleDefinition
```
---
## Step 3: Reference Module
To use your module in the Medusa backend, add your module to `medusa-config.js`:
```js title=medusa-config.js
module.exports = {
// ...
modules: {
// ...
moduleType: {
resolve: "module-name-or-path",
options: {
// options if necessary
},
// optional
resources: "shared",
},
},
}
```
The way you add your module depends on its type and what options it requires, if any. Note that in the above code example:
- `moduleType` is the type of your module. For example, if your module is a cache module, it should be changed to `cacheService`.
- `resolve` is used to reference the Module. Its value should be either the name of an NPM package module, or a relative file path to the module. This is explained more in the [Module Reference section](#module-reference).
- `options` should hold any options of your module, if necessary.
- `resources` is an optional property that indicates whether the module shares the same dependency container as the rest of the resources in the Medusa backend. More details are explained in the [Module Scope section](#module-scope).
### Module Reference
When the module is installed as an NPM package, the value of the `resolve` property should be the name of that package. For example:
```js title=medusa-config.js
module.exports = {
// ...
modules: {
// ...
moduleType: {
resolve: "custom-module",
// ...
},
},
}
```
However, when using a local module, you must reference the module using a relative file path to it from the Medusa backend.
For example, consider you have the following file structure:
```
|
|___ custom-module
| |
| |___ src
| |
| |___ index.ts
| |
| |___ services
| | |
| | |___ custom-service.ts
| |___ // more files
|
|
|___ medusa-backend
```
You can reference your module in two ways:
1\. Referencing the directory: In this case, it's assumed that the `index.ts` file that contains the module definition is in the root of the directory you referenced. Using the above example, the file path would be in this case:
```js title=medusa-config.js
module.exports = {
// ...
modules: {
// ...
moduleType: {
resolve: "../custom-module/src",
// ...
},
},
}
```
2\. Referencing `index` file: In this case, it's assumed that the `index.ts` or `index.js` file you're referencing includes the module definition. Using the above example, the file path would be in this case:
```js title=medusa-config.js
module.exports = {
// ...
modules: {
// ...
moduleType: {
resolve: "../custom-module/src/index.ts",
// ...
},
},
}
```
### Module Scope
By default, the module shares the same dependency container used across the Medusa backend. So, the module can benefit from the core services and other resources available through [dependency injection](../fundamentals/dependency-injection.md). The module can also benefit from the same database connection.
The module's scope can be changed using the `resources` property available as part of the module's configurations:
```js title=medusa-config.js
module.exports = {
// ...
modules: {
// ...
moduleType: {
// other configurations
resources: "shared",
},
},
}
```
The `resources` property can have one of the following values:
- `shared`: (default) The dependency container is shared with the module, including the database connection. You don't need to establish the database connection yourself in a loader.
- `isolated`: the module receives an empty dependency container, and only its own dependencies will be registered in the container. When using this value, you must establish the database connection yourself and managing other resources within your module.
---
## Step 4: Test Your Module
Finally, to test your module, run the following command:
```bash npm2yarn
npx medusa develop
```
This starts the Medusa backend and runs your module as part of it.
---
## Next Steps
After you finish developing your module, you can publish it as an NPM package with [this guide](./publish.md).