4.2.2. Service Factory

In this chapter, you’ll learn about what the service factory is and how to use it.

What is the Service Factory?#

Medusa provides a service factory that your module’s main service can extend.

The service factory generates data management methods for your data models, so you don't have to implement these methods manually.

Extend the service factory when
  • Your service provides data-management functionalities of your data models.

How to Extend the Service Factory?#

Medusa provides the service factory as a MedusaService function your service extends. The function creates and returns a service class with generated data-management methods.

For example, create the file src/modules/hello/service.ts with the following content:

src/modules/hello/service.ts
1import { MedusaService } from "@medusajs/utils"2import MyCustom from "./models/my-custom"3
4class HelloModuleService extends MedusaService({5  MyCustom,6}){7  // TODO implement custom methods8}9
10export default HelloModuleService

MedusaService Parameters#

The MedusaService function accepts one parameter, which is an object of data models to generate data-management methods for.

In the example above, since the HelloModuleService extends MedusaService, it has methods to manage the MyCustom data model, such as createMyCustoms.

Generated Methods#

The service factory generates data-management methods for each of the data models provided in the first parameter.

The method's names are the operation's name, suffixed by the data model's name.

For example, the following methods are generated for the code snippet above:

listMyCustoms#

This method retrieves an array of records based on filters and pagination configurations.

For example:

1const myCustoms = await helloModuleService2  .listMyCustoms()3
4// with filters5const myCustoms = await helloModuleService6  .listMyCustoms({7    id: ["123"]8  })

Using a Constructor#

If you implement the constructor of your service, make sure to call super passing it ...arguments.

For example:

1import { MedusaService } from "@medusajs/utils"2import MyCustom from "./models/my-custom"3
4class HelloModuleService extends MedusaService({5  MyCustom,6}){7  constructor() {8    super(...arguments)9  }10}11
12export default HelloModuleService
Was this chapter helpful?