* docs: migrate ui docs to docs universe * created yarn workspace * added eslint and tsconfig configurations * fix eslint configurations * fixed eslint configurations * shared tailwind configurations * added shared ui package * added more shared components * migrating more components * made details components shared * move InlineCode component * moved InputText * moved Loading component * Moved Modal component * moved Select components * Moved Tooltip component * moved Search components * moved ColorMode provider * Moved Notification components and providers * used icons package * use UI colors in api-reference * moved Navbar component * used Navbar and Search in UI docs * added Feedback to UI docs * general enhancements * fix color mode * added copy colors file from ui-preset * added features and enhancements to UI docs * move Sidebar component and provider * general fixes and preparations for deployment * update docusaurus version * adjusted versions * fix output directory * remove rootDirectory property * fix yarn.lock * moved code component * added vale for all docs MD and MDX * fix tests * fix vale error * fix deployment errors * change ignore commands * add output directory * fix docs test * general fixes * content fixes * fix announcement script * added changeset * fix vale checks * added nofilter option * fix vale error
678 lines
19 KiB
Plaintext
678 lines
19 KiB
Plaintext
---
|
||
description: 'Learn how to create a service in Medusa. This guide also includes how to use services in other services, subscribers, and endpoints.'
|
||
addHowToData: true
|
||
---
|
||
|
||
import Troubleshooting from '@site/src/components/Troubleshooting'
|
||
import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md'
|
||
import Tabs from '@theme/Tabs';
|
||
import TabItem from '@theme/TabItem';
|
||
|
||
# How to Create a Service
|
||
|
||
In this document, you’ll learn how you can create a [Service](./overview.mdx) 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](../fundamentals/dependency-injection.md), 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:
|
||
|
||
```ts title=/src/services/post.ts
|
||
import { TransactionBaseService } from "@medusajs/medusa"
|
||
|
||
class PostService extends TransactionBaseService {
|
||
getMessage() {
|
||
return `Welcome to My Store!`
|
||
}
|
||
}
|
||
|
||
export default PostService
|
||
```
|
||
|
||
This service will be registered in the [dependency container](../fundamentals/dependency-injection.md) 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:
|
||
|
||
```bash npm2yarn
|
||
npm run build
|
||
```
|
||
|
||
---
|
||
|
||
## Service Constructor
|
||
|
||
As the service extends the `TransactionBaseService` class, all resources registered in the dependency container can be accessed through [dependency injection](../fundamentals/dependency-injection.md). 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:
|
||
|
||
```ts title=/src/services/post.ts
|
||
import { ProductService } from "@medusajs/medusa"
|
||
import { PostRepository } from "../repositories/post"
|
||
|
||
class PostService extends TransactionBaseService {
|
||
private productService: ProductService
|
||
|
||
constructor(container) {
|
||
super(container)
|
||
this.productService = container.productService
|
||
}
|
||
// ...
|
||
}
|
||
```
|
||
|
||
Then, you can use that service anywhere in your custom service. For example:
|
||
|
||
```ts title=/src/services/post.ts
|
||
class PostService extends TransactionBaseService {
|
||
// ...
|
||
async getProductCount() {
|
||
return await this.productService.count()
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 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](../fundamentals/dependency-injection.md).
|
||
|
||
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:
|
||
|
||
```ts title=/src/services/post.ts
|
||
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](../entities/repositories.md) 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:
|
||
|
||
```ts title=/src/services/post.ts
|
||
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](https://github.com/jeffijoe/awilix), you can specify the [Lifetime](https://github.com/jeffijoe/awilix#lifetime-management) of a service. The lifetime is added as a static property to the service.
|
||
|
||
There are three lifetime types:
|
||
|
||
1. `Lifetime.TRANSIENT`: when used, a new instance of the service is created every time it is resolved in other resources from the dependency container.
|
||
2. `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.
|
||
3. `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:
|
||
|
||
```ts title=/src/services/post.ts
|
||
import { TransactionBaseService } from "@medusajs/medusa"
|
||
import { Lifetime } from "awilix"
|
||
|
||
class PostService extends TransactionBaseService {
|
||
static LIFE_TIME = Lifetime.SCOPED
|
||
|
||
// ...
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 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:
|
||
|
||
```ts title=/src/services/post.ts
|
||
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 endpoints. In these methods, it can be helpful to provide filtering and pagination utilities that can be used by endpoints 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:
|
||
|
||
1. `Selector`: Can be used to accepts the attributes of an entity as possible filtering parameters, based on each attribute's type.
|
||
2. `FindConfig`: Can be used to provide pagination parameters such as `skip`, `take`, and `relations`. `skip` indicates how many items to skip before retrieving the results, `take` indicates how many results to return, and `relations`, 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:
|
||
|
||
```ts title=src/services/post.ts
|
||
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:
|
||
|
||
```ts title=src/services/post.ts
|
||
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 endpoints or services that use this method can pass what relations to expand in the next parameter:
|
||
|
||
```ts
|
||
await postService.retrieve(id, {
|
||
relations: ["authors"],
|
||
})
|
||
```
|
||
|
||
---
|
||
|
||
## 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.
|
||
|
||
:::note
|
||
|
||
This assumes you're handling errors in your custom endpoints as explained [here](../endpoints/create.mdx#handle-errors).
|
||
|
||
:::
|
||
|
||
For example:
|
||
|
||
```ts title=src/services/post.ts
|
||
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.
|
||
|
||
:::note
|
||
|
||
Before using your service, make sure you run the [build command](#build-files).
|
||
|
||
:::
|
||
|
||
### 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:
|
||
|
||
```ts
|
||
class MyService extends TransactionBaseService {
|
||
constructor(container) {
|
||
super(container)
|
||
this.postService = container.postService
|
||
}
|
||
// ...
|
||
}
|
||
```
|
||
|
||
### In an Endpoint
|
||
|
||
To use your custom service in an endpoint, you can use `req.scope.resolve` passing it the service’s registration name:
|
||
|
||
```ts
|
||
const postService = req.scope.resolve("postService")
|
||
|
||
res.json({
|
||
posts: postService.list(),
|
||
})
|
||
```
|
||
|
||
### In a Subscriber
|
||
|
||
To use your custom service in a subscriber, you can have easy access to it in the subscriber’s dependencies injected to the constructor of your subscriber:
|
||
|
||
```ts
|
||
class MySubscriber {
|
||
constructor({ postService, eventBusService }) {
|
||
this.postService = postService
|
||
}
|
||
// ...
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Troubleshooting
|
||
|
||
<Troubleshooting
|
||
sections={[
|
||
{
|
||
title: 'AwilixResolutionError: Could Not Resolve X',
|
||
content: <ServiceLifetimeSection />
|
||
}
|
||
]}
|
||
/>
|
||
|
||
---
|
||
|
||
## 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](../entities/create.mdx#adding-relations) documentation to learn how to create the custom entities used in this example.
|
||
|
||
<Tabs groupId="files" isCodeTabs={true}>
|
||
<TabItem value="post" label="src/services/post.ts" default>
|
||
|
||
```ts
|
||
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
|
||
```
|
||
|
||
</TabItem>
|
||
<TabItem value="author" label="src/services/author.ts">
|
||
|
||
```ts
|
||
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
|
||
}
|
||
|
||
async create(
|
||
data: Pick<Author, "name" | "image">
|
||
): Promise<Author> {
|
||
return this.atomicPhase_(async (manager) => {
|
||
const authorRepo = manager.withRepository(
|
||
this.authorRepository_
|
||
)
|
||
const post = authorRepo.create(data)
|
||
const result = await authorRepo.save(post)
|
||
|
||
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 post = await this.retrieve(id)
|
||
|
||
Object.assign(post, data)
|
||
|
||
return await authorRepo.save(post)
|
||
})
|
||
}
|
||
|
||
async delete(id: string): Promise<void> {
|
||
return await this.atomicPhase_(async (manager) => {
|
||
const authorRepo = manager.withRepository(
|
||
this.authorRepository_
|
||
)
|
||
const post = await this.retrieve(id)
|
||
|
||
await authorRepo.remove([post])
|
||
})
|
||
}
|
||
}
|
||
|
||
export default AuthorService
|
||
```
|
||
|
||
</TabItem>
|
||
</Tabs>
|
||
|
||
---
|
||
|
||
## See Also
|
||
|
||
- [Create a Plugin](../plugins/create.mdx)
|