api-ref: custom API reference (#4770)

* initialized next.js project

* finished markdown sections

* added operation schema component

* change page metadata

* eslint fixes

* fixes related to deployment

* added response schema

* resolve max stack issue

* support for different property types

* added support for property types

* added loading for components

* added more loading

* type fixes

* added oneOf type

* removed console

* fix replace with push

* refactored everything

* use static content for description

* fixes and improvements

* added code examples section

* fix path name

* optimizations

* fixed tag navigation

* add support for admin and store references

* general enhancements

* optimizations and fixes

* fixes and enhancements

* added search bar

* loading enhancements

* added loading

* added code blocks

* added margin top

* add empty response text

* fixed oneOf parameters

* added path and query parameters

* general fixes

* added base path env variable

* small fix for arrays

* enhancements

* design enhancements

* general enhancements

* fix isRequired

* added enum values

* enhancements

* general fixes

* general fixes

* changed oas generation script

* additions to the introduction section

* added copy button for code + other enhancements

* fix response code block

* fix metadata

* formatted store introduction

* move sidebar logic to Tags component

* added test env variables

* fix code block bug

* added loading animation

* added expand param + loading

* enhance operation loading

* made responsive + improvements

* added loading provider

* fixed loading

* adjustments for small devices

* added sidebar label for endpoints

* added feedback component

* fixed analytics

* general fixes

* listen to scroll for other headings

* added sample env file

* update api ref files + support new fields

* fix for external docs link

* added new sections

* fix last item in sidebar not showing

* move docs content to www/docs

* change redirect url

* revert change

* resolve build errors

* configure rewrites

* changed to environment variable url

* revert changing environment variable name

* add environment variable for API path

* fix links

* fix tailwind settings

* remove vercel file

* reconfigured api route

* move api page under api

* fix page metadata

* fix external link in navigation bar

* update api spec

* updated api specs

* fixed google lint error

* add max-height on request samples

* add padding before loading

* fix for one of name

* fix undefined types

* general fixes

* remove response schema example

* redesigned navigation bar

* redesigned sidebar

* fixed up paddings

* added feedback component + report issue

* fixed up typography, padding, and general styling

* redesigned code blocks

* optimization

* added error timeout

* fixes

* added indexing with algolia + fixes

* fix errors with algolia script

* redesign operation sections

* fix heading scroll

* design fixes

* fix padding

* fix padding + scroll issues

* fix scroll issues

* improve scroll performance

* fixes for safari

* optimization and fixes

* fixes to docs + details animation

* padding fixes for code block

* added tab animation

* fixed incorrect link

* added selection styling

* fix lint errors

* redesigned details component

* added detailed feedback form

* api reference fixes

* fix tabs

* upgrade + fixes

* updated documentation links

* optimizations to sidebar items

* fix spacing in sidebar item

* optimizations and fixes

* fix endpoint path styling

* remove margin

* final fixes

* change margin on small devices

* generated OAS

* fixes for mobile

* added feedback modal

* optimize dark mode button

* fixed color mode useeffect

* minimize dom size

* use new style system

* radius and spacing design system

* design fixes

* fix eslint errors

* added meta files

* change cron schedule

* fix docusaurus configurations

* added operating system to feedback data

* change content directory name

* fixes to contribution guidelines

* revert renaming content

* added api-reference to documentation workflow

* fixes for search

* added dark mode + fixes

* oas fixes

* handle bugs

* added code examples for clients

* changed tooltip text

* change authentication to card

* change page title based on selected section

* redesigned mobile navbar

* fix icon colors

* fix key colors

* fix medusa-js installation command

* change external regex in algolia

* change changeset

* fix padding on mobile

* fix hydration error

* update depedencies
This commit is contained in:
Shahed Nasser
2023-08-15 18:07:54 +03:00
committed by GitHub
parent 16249ec280
commit 914d773d3a
3270 changed files with 22075 additions and 192064 deletions
@@ -0,0 +1,677 @@
---
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, youll 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 constructors dependencies and set it to a field inside your services 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 everytime 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 utilitizing 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 services 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 subscribers 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)
@@ -0,0 +1,102 @@
---
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'
# How to Extend a Service
In this document, youll learn how to extend a core service in Medusa.
## Overview
Medusas core services cover a wide range of functionalities related to each domain or entity. You can extend these services to add custom methods or override existing methods.
### Word of Caution about Overriding
Extending services to add new methods shouldn't cause any issues within your commerce application. However, if you extend them to override their existing methods, you should be aware that this could have negative implications, such as unanticipated bugs, especially when you try to upgrade the core Medusa package to a newer version.
---
## Step 1: Create the Service File
In your Medusa backend, create the file `src/services/product.ts`. This file will hold your extended service.
Note that the name of the file must be the same as the name of the original service in the core package. So, if youre extending the `ProductService`, the files name should be `product.ts`. On the other hand, if youre extending the `CustomerService`, the files name should be `customer.ts`.
---
## Step 2: Implementing the Service
In the file, you can import the original service from the Medusa core, then create your service that extends the core service.
For example, to extend the Product service:
```ts title=src/services/product.ts
import {
ProductService as MedusaProductService,
} from "@medusajs/medusa"
class ProductService extends MedusaProductService {
// TODO add customizations
}
export default ProductService
```
Notice that you alias the `ProductService` of the core to avoid naming conflicts.
Within the service, you can add new methods or extend existing ones.
You can also change the lifetime of the service:
```ts title=src/services/product.ts
import { Lifetime } from "awilix"
import {
ProductService as MedusaProductService,
} from "@medusajs/medusa"
class ProductService extends MedusaProductService {
// The default life time for a core service is SINGLETON
static LIFE_TIME = Lifetime.SCOPED
// ...
}
export default ProductService
```
You can learn more details about the service lifetime and other considerations when creating a service in the [Create Service documentation](./create-service.mdx).
---
## Step 3: Test it Out
To test out your customization, start by transpiling your files by running the following command in the root directory of the Medusa backend:
```bash npm2yarn
npm run build
```
Then, start the backend:
```bash npm2yarn
npx medusa develop
```
You should see the customizations you made in effect.
---
## Troubleshooting
<Troubleshooting
sections={[
{
title: 'AwilixResolutionError: Could Not Resolve X (Service Lifetime)',
content: <ServiceLifetimeSection />
}
]}
/>
@@ -0,0 +1,63 @@
---
description: 'Learn what Services are in Medusa. Services represent bundled helper methods that you want to use across your commerce application.'
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Services
In this document, you'll learn about what Services are in Medusa.
## What are Services
Services in Medusa represent bundled helper methods that you want to use across your commerce application. By convention, they represent a certain entity or functionality in Medusa.
For example, you can use Medusas `productService` to get the list of products, as well as perform other functionalities related to products. Theres also an `authService` that provides functionalities like authenticating customers and users.
In the Medusa backend, custom services are TypeScript or JavaScript files located in the `src/services` directory. Each service should be a class that extends the `TransactionBaseService` class from the core Medusa package `@medusajs/medusa`. Each file you create in `src/services` should hold one service and export it.
The file name is important as it determines the name of the service when you need to use it elsewhere. The name of the service will be registered in the dependency container as the camel-case version of the file name with `Service` appended to the end of the name. Other resources, such as other services or endpoints, will use that name when resolving the service from the dependency container.
For example, if the file name is `hello.ts`, the service will be registered as `helloService` in the dependency container. If the file name is `hello-world.ts`, the service name will be registered as `helloWorldService`.
:::note
You can learn more about the dependency container and how it works in the [dependency injection](../fundamentals/dependency-injection.md) documentation.
:::
The service must then be transpiled using the `build` command, which moves them to the `dist` directory, to be used across your commerce application.
:::tip
If you're creating a service in a plugin, learn more about the required structure [here](../plugins/create.mdx#plugin-structure).
:::
---
## Custom Development
Developers can create custom services in the Medusa backend, a plugin, or in a module.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/services/create-service',
label: 'Create a Service',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a service in Medusa.'
}
},
{
type: 'link',
href: '/development/services/extend-service',
label: 'Extend a Service',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to extend a core Medusa service.'
}
},
]} />