How to Create a Service
In this document, you’ll learn how you can create a Service and use it across your Medusa backend just like any of the core services.
Basic Service Implementation
To create a service, create a TypeScript or JavaScript file in src/services
to hold the service. The name of the file should be the name of the service without Service
. This is essential as the file name is used when registering the service in the dependency container, and Service
is appended to the camel-case version of the file name automatically.
For example, if you want to create a service PostService
, eventually registered as postService
, create the file post.ts
in src/services
with the following content:
This service will be registered in the dependency container as postService
. It contains a single sample method getMessage
.
Build Files
Custom services must be transpiled and moved to the dist
directory before you can start consuming them. When you run your backend using either the medusa develop
or npx medusa develop
commands, it watches the files under src
for any changes, then triggers the build
command and restarts the server.
However, the build isn't triggered when the backend first starts running, and it's never triggered when the medusa start
or npx medusa start
commands are used.
So, make sure to run the build
command before starting the backend:
Service Constructor
As the service extends the TransactionBaseService
class, all resources registered in the dependency container can be accessed through dependency injection. This includes services, repositories, and other resources in the Medusa core, as well as your custom services and resources.
So, if you want your service to use another service, add it as part of your constructor’s dependencies and set it to a field inside your service’s class:
Then, you can use that service anywhere in your custom service. For example:
Use Repositories
As your service provides helper methods related to one or more entities in your backend, you'll need to perform operations on that entity. To do that, you need to use the entity's repository.
Repositories, just like services, are registered in the dependency container and can be accessed with dependency injection.
However, to actually get an instance of the repository within the service's methods, you need to use the service's activeManager_
, which is declared in the parent class TransactionBaseService
. activeManager_
is an instance of Typeorm's EntityManager
and has a method withRepository
which allows you to retrieve an instance of the repository.
For example:
import { PostRepository } from "../repositories/post"
class PostService extends TransactionBaseService {
// ...
protected postRepository_: typeof PostRepository
constructor(container) {
super(container)
// ...
this.postRepository_ = container.postRepository
}
async list(): Promise<Post[]> {
const postRepo = this.activeManager_.withRepository(
this.postRepository_
)
return await postRepo.find()
}
// ...
}
Refer to the repositories documentation to learn about its different methods.
Transactions
Transactions ensure that when an error occurs, all data manipulation within the transaction is reverted. As services are likely to include methods that manipulate data, such as create or update a post, it's very useful to wrap that logic within a transaction block.
Since services extend the TransactionBaseService
class, you can use its atomicPhase_
method. The atomicPhase_
method allows you to wrap code within a transactional block.
It accepts as a parameter a function, which includes the logic to be performed inside the transactional block. The function accepts as a parameter a transaction manager, which is Typeorm's EntityManager
. You can use it within the function to retrieve repositories, among other functionalities.
The data returned by the function passed as a parameter to the atomicPhase_
method will be return by the atomicPhase_
method as well.
For example, the PostService
's create
method with the atomicPhase_
method:
class PostService extends TransactionBaseService {
protected postRepository_: typeof PostRepository
// ...
async create(
data: Pick<Post, "title" | "author_id">
): Promise<Post> {
return this.atomicPhase_(async (manager) => {
const postRepo = manager.withRepository(
this.postRepository_
)
const post = postRepo.create()
post.title = data.title
post.author_id = data.author_id
const result = await postRepo.save(post)
return result
})
}
}
Service Life Time
As the dependency container in Medusa is built on top of awilix, you can specify the Lifetime of a service. The lifetime is added as a static property to the service.
There are three lifetime types:
Lifetime.TRANSIENT
: when used, a new instance of the service is created every time it is resolved in other resources from the dependency container.Lifetime.SCOPED
: (default for custom services) when used, an instance of the service is created and reused in the scope of the dependency container. So, when the service is resolved in other resources that share that dependency container, the same instance of the service will be returned.Lifetime.SINGLETON
: (default for core services) when used, the service is always reused, regardless of the scope. An instance of the service is cached in the root container.
You can set the lifetime of your service by setting the LIFE_TIME
static property:
Retrieve Medusa Configurations
Within your service, you may need to access the Medusa configuration exported from medusa-config.js
. To do that, you can access configModule
using dependency injection.
For example:
import {
ConfigModule,
TransactionBaseService,
} from "@medusajs/medusa"
class PostService extends TransactionBaseService {
protected readonly configModule_: ConfigModule
constructor(container) {
super(container)
// ...
this.configModule_ = container.configModule
}
getConfigurations() {
return this.configModule_
}
// ...
}
export default PostService
Pagination, Filtering, and Relations
Often, your service will provide methods that retrieve a list of items, which can be used by API Routes. In these methods, it can be helpful to provide filtering and pagination utilities that can be used by API Routes or any other resources utilizing this service.
The @medusajs/medusa
package provides the following generic types that you can use to create the signature of your method that accepts filtering and pagination parameters:
Selector
: Can be used to accepts the attributes of an entity as possible filtering parameters, based on each attribute's type.FindConfig
: Can be used to provide pagination parameters such asskip
,take
, andrelations
.skip
indicates how many items to skip before retrieving the results,take
indicates how many results to return, andrelations
, indicate which relations to expand and include in the returned objects.
The @medusajs/medusa
package also provides a buildQuery
method that allows you to pass two parameter, the first of type Selector
and the second of type FindConfig
, to build the object that should be passed to the repository.
So, for example, to create a method that retrieves a list of posts and the total number of posts available:
import {
FindConfig,
Selector,
TransactionBaseService,
buildQuery,
} from "@medusajs/medusa"
class PostService extends TransactionBaseService {
// ...
async listAndCount(
selector?: Selector<Post>,
config: FindConfig<Post> = {
skip: 0,
take: 20,
relations: [],
}): Promise<[Post[], number]> {
const postRepo = this.activeManager_.withRepository(
this.postRepository_
)
const query = buildQuery(selector, config)
return postRepo.findAndCount(query)
}
}
In addition, you can expand relations when retrieving a single item with the help of FindConfig
and buildQuery
.
For example, to create a method that retrieves a single post:
import {
FindConfig,
TransactionBaseService,
buildQuery,
} from "@medusajs/medusa"
import { MedusaError } from "@medusajs/utils"
class PostService extends TransactionBaseService {
// ...
async retrieve(
id: string,
config?: FindConfig<Post>
): Promise<Post> {
const postRepo = this.activeManager_.withRepository(
this.postRepository_
)
const query = buildQuery({
id,
}, config)
const post = await postRepo.findOne(query)
if (!post) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
"Post was not found"
)
}
return post
}
}
Then, any other resources such as API Route or services that use this method can pass what relations to expand in the next parameter:
Throwing Errors
When you need to throw errors in your service methods, it's recommended to use MedusaError
imported from @medusajs/util
. That way, when an error is thrown within a request, the error will be returned in the response in a consistent format as Medusa's errors.
This assumes you're handling errors in your custom API Route as explained here.
For example:
import { MedusaError } from "@medusajs/utils"
class PostService extends TransactionBaseService {
// ...
async retrieve(
id: string,
config?: FindConfig<Post>
): Promise<Post> {
const postRepo = this.activeManager_.withRepository(
this.postRepository_
)
const query = buildQuery({
id,
}, config)
const post = await postRepo.findOne(query)
if (!post) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
"Post was not found"
)
}
return post
}
}
Use a Service
In this section, you'll learn how to use services throughout your Medusa backend. This includes both Medusa's services and your custom services.
Before using your service, make sure you run the build command.
In a Service
To use your custom service in another custom service, you can have easy access to it in the dependencies injected to the constructor of your service:
In an API Route
To use your custom service in an API Route, you can use MedusaRequest
object's scope.resolve
method passing it the service’s registration name:
In a Subscriber
To resolve your custom service in subscriber handler functions, use the container
property of the handler function's parameter. The container
has a method resolve
which accepts the registration name of the service as a parameter.
For example:
import {
type SubscriberConfig,
type SubscriberArgs,
} from "@medusajs/medusa"
import { PostService } from "../services/post.ts"
export default async function postHandler({
data, eventName, container, pluginOptions,
}: SubscriberArgs<Record<string, string>>) {
const postService: PostService = container.resolve(
"postService"
)
// ...
}
// ...
Troubleshooting
AwilixResolutionError: Could Not Resolve X
Example: Services with CRUD Operations
In this section, you'll find a full example of the PostService
and AuthorService
that implement Create, Read, Update, and Delete (CRUD) operations.
You can refer to the Entities documentation to learn how to create the custom entities used in this example.
import {
FindConfig,
Selector,
TransactionBaseService,
buildQuery,
} from "@medusajs/medusa"
import { PostRepository } from "../repositories/post"
import { Post } from "../models/post"
import { MedusaError } from "@medusajs/utils"
class PostService extends TransactionBaseService {
protected postRepository_: typeof PostRepository
constructor(container) {
super(container)
this.postRepository_ = container.postRepository
}
async listAndCount(
selector?: Selector<Post>,
config: FindConfig<Post> = {
skip: 0,
take: 20,
relations: [],
}): Promise<[Post[], number]> {
const postRepo = this.activeManager_.withRepository(
this.postRepository_
)
const query = buildQuery(selector, config)
return postRepo.findAndCount(query)
}
async list(
selector?: Selector<Post>,
config: FindConfig<Post> = {
skip: 0,
take: 20,
relations: [],
}): Promise<Post[]> {
const [posts] = await this.listAndCount(selector, config)
return posts
}
async retrieve(
id: string,
config?: FindConfig<Post>
): Promise<Post> {
const postRepo = this.activeManager_.withRepository(
this.postRepository_
)
const query = buildQuery({
id,
}, config)
const post = await postRepo.findOne(query)
if (!post) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
"Post was not found"
)
}
return post
}
async create(
data: Pick<Post, "title" | "author_id">
): Promise<Post> {
return this.atomicPhase_(async (manager) => {
const postRepo = manager.withRepository(
this.postRepository_
)
const post = postRepo.create()
post.title = data.title
post.author_id = data.author_id
const result = await postRepo.save(post)
return result
})
}
async update(
id: string,
data: Omit<Partial<Post>, "id">
): Promise<Post> {
return await this.atomicPhase_(async (manager) => {
const postRepo = manager.withRepository(
this.postRepository_
)
const post = await this.retrieve(id)
Object.assign(post, data)
return await postRepo.save(post)
})
}
async delete(id: string): Promise<void> {
return await this.atomicPhase_(async (manager) => {
const postRepo = manager.withRepository(
this.postRepository_
)
const post = await this.retrieve(id)
await postRepo.remove([post])
})
}
}
export default PostService
import {
FindConfig,
Selector,
TransactionBaseService,
buildQuery,
} from "@medusajs/medusa"
import { EntityManager } from "typeorm"
import AuthorRepository from "../repositories/author"
import { Author } from "../models/author"
import { MedusaError } from "@medusajs/utils"
class AuthorService extends TransactionBaseService {
protected manager_: EntityManager
protected transactionManager_: EntityManager
protected authorRepository_: typeof AuthorRepository
constructor(container) {
super(container)
this.authorRepository_ = container.authorRepository
}
async listAndCount(
selector?: Selector<Author>,
config: FindConfig<Author> = {
skip: 0,
take: 20,
relations: [],
}): Promise<[Author[], number]> {
const authorRepo = this.activeManager_.withRepository(
this.authorRepository_
)
const query = buildQuery(selector, config)
return authorRepo.findAndCount(query)
}
async list(
selector?: Selector<Author>,
config: FindConfig<Author> = {
skip: 0,
take: 20,
relations: [],
}): Promise<Author[]> {
const [authors] = await this.listAndCount(selector, config)
return authors
}
async retrieve(
id: string,
config?: FindConfig<Author>
): Promise<Author> {
const authorRepo = this.activeManager_.withRepository(
this.authorRepository_
)
const query = buildQuery({
id,
}, config)
const author = await authorRepo.findOne(query)
if (!author) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
"Author was not found"
)
}
return author
}
async create(
data: Pick<Author, "name" | "image">
): Promise<Author> {
return this.atomicPhase_(async (manager) => {
const authorRepo = manager.withRepository(
this.authorRepository_
)
const author = authorRepo.create(data)
const result = await authorRepo.save(author)
return result
})
}
async update(
id: string,
data: Omit<Partial<Author>, "id">
): Promise<Author> {
return await this.atomicPhase_(async (manager) => {
const authorRepo = manager.withRepository(
this.authorRepository_
)
const author = await this.retrieve(id)
Object.assign(author, data)
return await authorRepo.save(author)
})
}
async delete(id: string): Promise<void> {
return await this.atomicPhase_(async (manager) => {
const authorRepo = manager.withRepository(
this.authorRepository_
)
const author = await this.retrieve(id)
await authorRepo.remove([author])
})
}
}
export default AuthorService