4.3.4. 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 in the database, so you don't have to implement these methods manually.

Extend the service factory whenYour 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/framework/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 methods to manage the records of each of the data models provided in the first parameter in the database.

The method's names are the operation's name, suffixed by the data model's key in the object parameter passed to MedusaService.

For example, the following methods are generated for the service above:

NoteFind a complete reference of each of the methods in this documentation

listMyCustoms#

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

For example:

Code
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:

Code
1import { MedusaService } from "@medusajs/framework/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?
Edit this page