Documentation

4.1.1. Implement Brand Module

Example ChapterThis chapter covers how to create a Brand Module as part of the "Build Custom Features" chapter .

1. Create Module Directory#

Start by creating the directory src/modules/brand that will hold the Brand Module's files.


2. Create Data Model#

To create a data model that represents a new brand table in the database, create the file src/modules/brand/models/brand.ts with the following content:

src/modules/brand/models/brand.ts
1import { model } from "@medusajs/utils"2
3export const Brand = model.define("brand", {4  id: model.id().primaryKey(),5  name: model.text(),6})

This creates a Brand data model which has an id primary key property, and a name text property.


3. Create Module Service#

Next, you'll create the module's main service that manages the Brand data model.

Create the file src/modules/brand/service.ts with the following content:

src/modules/brand/service.ts
1import { MedusaService } from "@medusajs/utils"2import { Brand } from "./models/brand"3
4class BrandModuleService extends MedusaService({5  Brand,6}) {7
8}9
10export default BrandModuleService

The BrandModuleService extends a MedusaService function imported from @medusajs/utils which is a service factory.

The MedusaService function receives an object of the module's data models as a parameter, and generates methods to manage those data models, such as createBrands and updateBrands.

Those methods are now available at the BrandModuleService class and you'll use them in upcoming steps.

TipFind a reference of the generated methods in this guide .

4. Create Module's Definition#

To export the module's definition, create the file src/modules/brand/index.ts with the following content:

src/modules/brand/index.ts
1import { Module } from "@medusajs/utils"2import BrandModuleService from "./service"3
4export const BRAND_MODULE = "brandModuleService"5
6export default Module(BRAND_MODULE, {7  service: BrandModuleService,8})

This exposes the module to your application and allows you to resolve the BrandModuleService, which is its main service.

NoteLearn more about modules and services in this guide .

5. Register Module in Config#

Finally, add the module to Medusa's configurations in medusa-config.js:

medusa-config.js
1module.exports = defineConfig({2  // ...3  modules: {4    brandModuleService: {5      resolve: "./modules/brand",6    },7  },8})

6. Generate and Run Migrations#

To reflect the data model in the database, generate migrations for the brandModuleService module and migrate the changes to the database:

Terminal
npx medusa db:generate brandModuleServicenpx medusa db:migrate

Next Step: Create Brand Workflow#

In the next step, you'll create a workflow whose steps use the Brand Module's main service to create a brand.

Was this chapter helpful?
Edit this page