3.3.6. 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, saving you time on implementing these methods manually.
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/blog/service.ts
with the following content:
MedusaService Parameters#
The MedusaService
function accepts one parameter, which is an object of data models for which to generate data-management methods.
In the example above, since the BlogModuleService
extends MedusaService
, it has methods to manage the Post
data model, such as createPosts
.
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 names are the operation 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:
listPosts#
This method retrieves an array of records based on filters and pagination configurations.
For example:
Using a Constructor#
If you implement a constructor
in your service, make sure to call super
and pass it ...arguments
.
For example:
Generated Internal Services#
The service factory also generates internal services for each data model passed to the MedusaService
function. These services are registered in the module's container and can be resolved using their camel-cased names.
For example, if the BlogModuleService
is defined as follows:
Then, you'll have a postService
registered in the module's container that allows you to manage posts.
Generated internal services have the same methods as the BlogModuleService
, such as create
, retrieve
, update
, and delete
, but without the data model name suffix.
These services are useful when you need to perform database operations in loaders, as they are executed before the module's services are registered. Learn more in the Module Container documentation.
For example, you can create a loader that logs the number of posts in the database:
1import { LoaderOptions } from "@medusajs/framework/types"2 3export default async function helloWorldLoader({4 container,5}: LoaderOptions) {6 const postService = container.resolve("postService")7 8 const [_, count] = await postService.listAndCount()9 10 console.log(`[helloWorldLoader]: There are ${count} posts in the database.`)11}