docs: combine endpoints documentations (#2396)

* docs: combined endpoint docs

* fixed links
This commit is contained in:
Shahed Nasser
2022-10-10 15:55:39 +03:00
committed by GitHub
parent a23ecf4724
commit 9bc57abca3
7 changed files with 264 additions and 449 deletions
@@ -1,220 +0,0 @@
# Create Endpoint for Admin
In this document, youll learn how to add a custom endpoint in the Backend that you can use from the Admin.
## Overview
Custom endpoints reside under the `src/api` directory in your Medusa Backend. To define a new endpoint, you can add the file `index.js` under the `src/api` directory. This file should export a function that returns an Express router.
Your endpoint can be under any path you wish. By Medusas conventions, all Admin REST APIs are prefixed by `/admin`. For example, the `/admin/products` lets you retrieve the products to display them on your Admin.
## Implementation
To create a new endpoint, start by creating a new file in `src/api` called `index.js`. At its basic format, `index.js` should look something like this:
```js
import { Router } from "express"
export default () => {
const router = Router()
router.get("/admin/hello", (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
return router
}
```
This exports a function that returns an Express router. In that function, you can create one or more endpoints. In the example above, you create the endpoint `/admin/hello`.
Now, if you run your server and send a request to `/admin/hello`, you will receive a JSON response message.
:::note
Custom endpoints are compiled into the `dist` directory of your Backend when you run your server using `medusa develop`, while its running, and when you run:
```bash npm2yarn
npm run build
```
:::
## Accessing Endpoints from Admin
If youre customizing the admin dashboard or creating your own, you need to use the `cors` library. A `OPTIONS` request should be added for each route and handle the requests with the `cors` library.
First, you need to import your Medusas configurations along with the `cors` library:
```js
import cors from "cors"
import { projectConfig } from "../../medusa-config"
```
Then, create an object that will hold the Cross-Origin Resource Sharing (CORS) configurations:
```js
const corsOptions = {
origin: projectConfig.admin_cors.split(","),
credentials: true,
}
```
Finally, for each route you add, create an `OPTIONS` request and add `cors` as a middleware for the route:
```js
router.options("/admin/hello", cors(corsOptions))
router.get("/admin/hello", cors(corsOptions), (req, res) => {
//...
})
```
## Multiple Endpoints
### Same File
You can add more than one endpoints in `src/api/index.js`:
```js
router.get("/admin/hello", (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
router.get("/admin/bye", (req, res) => {
res.json({
message: "Come back again!",
})
})
```
### Multiple Files
Alternatively, you can add multiple files for each endpoint or set of endpoints for readability and easy maintenance.
To do that with the previous example, first, create the file `src/api/hello.js` with the following content:
```js
export default (router) => {
router.get("/admin/hello", (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
}
```
You export a function that receives an Express router as a parameter and adds the endpoint `admin/hello` to it.
Next, create the file `src/api/bye.js` with the following content:
```js
export default (router) => {
router.get("/admin/bye", (req, res) => {
res.json({
message: "Come back again!",
})
})
}
```
Again, you export a function that receives an Express router as a parameter and adds the endpoint `admin/bye` to it.
Finally, in `src/api/index.js` import the two functions at the beginning of the file:
```js
import helloRoute from "./hello"
import byeRoute from "./bye"
```
and in the exported function, call each of the functions passing them the Express router:
```js
export default () => {
const router = Router()
helloRoute(router)
byeRoute(router)
return router
}
```
## Use Services
Services in Medusa bundle a set of functionalities into one class. Then, you can use that class anywhere in your Backend. For example, you can use the `ProductService` to retrieve products or perform operations like creating or updating a product.
You can retrieve any registered service in your endpoint using `req.scope.resolve` passing it the services registration name.
Heres an example of an endpoint that retrieves the count of products in your store:
```js
router.get("/admin/products/count", (req, res) => {
const productService = req.scope.resolve("productService")
productService.count().then((count) => {
res.json({
count,
})
})
})
```
The `productService` has a `count` method that returns a Promise. This Promise resolves to the count of the products. You return a JSON of the product count.
## Protected Routes
Protected routes are routes that should be accessible by logged-in users only.
To make a route protected, first, import the `authenticate` middleware:
```js
import authenticate from "@medusajs/medusa/dist/api/middlewares/authenticate"
```
Then, add the middleware to your route:
```js
router.get("/store/products/count", authenticate(), (req, res) => {
//...
})
```
Now, only authenticated users can access this endpoint.
### Accessing Current User
You can get the logged-in user ID using `req.user`:
```js
const id = req.user.userId
```
To get the users details, you can use the `userService`:
```js
const id = req.user.userId
const userService = req.scope.resolve("userService")
const user = await userService.retrieve(id)
```
### Route Parameters
The routes you create receive two parameters. The first one is the absolute path to the root directory that your server is running from. The second one is an object that has your plugin's options. If your API route is not implemented in a plugin, then it will be an empty object.
```js
export default (rootDirectory, pluginOptions) => {
const router = Router()
//...
}
```
## Whats Next
- [Learn how to add an endpoint for the Storefront.](/advanced/backend/endpoints/add-storefront)
- [Check out the API reference for all available endpoints.](https://docs.medusajs.com/api/admin)
@@ -1,219 +0,0 @@
# Create Endpoint for Storefront
In this document, youll learn how to add a custom endpoint in the Backend that you can use from the Storefront.
## Overview
Custom endpoints reside under the `src/api` directory in your Medusa Backend. To define a new endpoint, you can add the file `index.js` under the `src/api` directory. This file should export a function that returns an Express router.
Your endpoint can be under any path you wish. By Medusas conventions, all Storefront REST APIs are prefixed by `/store`. For example, the `/store/products` lets you retrieve the products to display them on your storefront.
## Implementation
To create a new endpoint, start by creating a new file in `src/api` called `index.js`. At its basic format, `index.js` should look something like this:
```js
import { Router } from "express"
export default () => {
const router = Router()
router.get("/store/hello", (req, res) => {
res.json({
message: "Welcome to My Store!",
})
})
return router
}
```
This exports a function that returns an Express router. In that function, you can create one or more endpoints. In the example above, you create the endpoint `/store/hello`.
Now, if you run your server and send a request to `/store/hello`, you will receive a JSON response message.
:::note
Custom endpoints are compiled into the `dist` directory of your Backend when you run your server using `medusa develop`, while its running, and when you run:
```bash npm2yarn
npm run build
```
:::
## Accessing Endpoints from Storefront
If youre customizing one of our storefronts or creating your own, you need to use the `cors` library.
First, you need to import your Medusas configurations along with the `cors` library:
```js
import cors from "cors"
import { projectConfig } from "../../medusa-config"
```
Then, create an object that will hold the Cross-Origin Resource Sharing (CORS) configurations:
```js
const corsOptions = {
origin: projectConfig.store_cors.split(","),
credentials: true,
}
```
Finally, for each route add `cors` as a middleware for the route passing it `corsOptions`:
```js
router.get("/store/hello", cors(corsOptions), (req, res) => {
//...
})
```
## Multiple Endpoints
### Same File
You can add more than one endpoints in `src/api/index.js`:
```js
router.get("/store/hello", (req, res) => {
res.json({
message: "Welcome to My Store!",
})
})
router.get("/store/bye", (req, res) => {
res.json({
message: "Come back again!",
})
})
```
### Multiple Files
Alternatively, you can add multiple files for each endpoint or set of endpoints for readability and easy maintenance.
To do that with the previous example, first, create the file `src/api/hello.js` with the following content:
```js
export default (router) => {
router.get("/store/hello", (req, res) => {
res.json({
message: "Welcome to My Store!",
})
})
}
```
You export a function that receives an Express router as a parameter and adds the endpoint `store/hello` to it.
Next, create the file `src/api/bye.js` with the following content:
```js
export default (router) => {
router.get("/store/bye", (req, res) => {
res.json({
message: "Come back again!",
})
})
}
```
Again, you export a function that receives an Express router as a parameter and adds the endpoint `store/bye` to it.
Finally, in `src/api/index.js` import the two functions at the beginning of the file:
```js
import helloRoute from "./hello"
import byeRoute from "./bye"
```
and in the exported function, call each of the functions passing them the Express router:
```js
export default () => {
const router = Router()
helloRoute(router)
byeRoute(router)
return router
}
```
## Use Services
Services in Medusa bundle a set of functionalities into one class. Then, you can use that class anywhere in your Backend. For example, you can use the `ProductService` to retrieve products or perform operations like creating or updating a product.
You can retrieve any registered service in your endpoint using `req.scope.resolve` passing it the services registration name.
Heres an example of an endpoint that retrieves the count of products in your store:
```js
router.get("/store/products/count", (req, res) => {
const productService = req.scope.resolve("productService")
productService.count().then((count) => {
res.json({
count,
})
})
})
```
The `productService` has a `count` method that returns a Promise. This Promise resolves to the count of the products. You return a JSON of the product count.
## Protected Routes
Protected routes are routes that should be accessible by logged-in customers only.
To make a route protected, first, import the `authenticate` middleware:
```js
import authenticate from "@medusajs/medusa/dist/api/middlewares/authenticate-customer"
```
Then, add the middleware to your route:
```jsx
router.get("/store/products/count", authenticate(), (req, res) => {
//...
})
```
Now, only authenticated users can access this endpoint.
### Accessing Current Customer
You can get the logged-in customers ID using `req.user`:
```jsx
const id = req.user.customer_id
```
To get the customers details, you can use the `customerService`:
```jsx
const id = req.user.customer_id
const customerService = req.scope.resolve("customerService")
const customer = await customerService.retrieve(id)
```
### Route Parameters
The routes you create receive two parameters. The first one is the absolute path to the root directory that your server is running from. The second one is an object that has your plugin's options. If your API route is not implemented in a plugin, then it will be an empty object.
```js
export default (rootDirectory, pluginOptions) => {
const router = Router()
//...
}
```
## Whats Next
- [Learn how to add an endpoint for the Admin.](/advanced/backend/endpoints/add-admin)
- [Check out the API reference for all available endpoints.](https://docs.medusajs.com/api/store)
@@ -0,0 +1,259 @@
# How to Create Endpoints
In this document, youll learn how to create endpoints in your Medusa server.
## Overview
Custom endpoints reside under the `src/api` directory in your Medusa Backend. To define a new endpoint, you can add the file `index.js` under the `src/api` directory. This file should export a function that returns an Express router.
## Implementation
To create a new endpoint, start by creating a new file in `src/api` called `index.js`. At its basic format, `index.js` should look something like this:
```jsx
import { Router } from "express"
export default (rootDirectory, pluginOptions) => {
const router = Router()
router.get("/hello", (req, res) => {
res.json({
message: "Welcome to My Store!",
})
})
return router
}
```
This exports a function that returns an Express router. The function receives two parameters:
- `rootDirectory` is the absolute path to the root directory that your server is running from.
- `pluginOptions` is an object that has your plugin's options. If your API route is not implemented in a plugin, then it will be an empty object.
### Endpoints Path
Your endpoint can be under any path you wish.
By Medusas conventions:
- All Storefront REST APIs are prefixed by `/store`. For example, the `/store/products` endpoint lets you retrieve the products to display them on your storefront.
- All Admin REST APIs are prefixed by `/admin`. For example, the `/admin/products` endpoint lets you retrieve the products to display them on your Admin.
You can also create endpoints that do not reside under these two prefixes, similar to the `hello` endpoint in the previous example.
## CORS Configuration
If youre adding a storefront or admin endpoint and you want to access these endpoints from the storefront or Medusa admin, you need to pass your endpoints Cross-Origin Resource Origin (CORS) options using the `cors` package.
First, you need to import your Medusa configurations along with the `cors` library:
```jsx
import cors from "cors"
import { projectConfig } from "../../medusa-config"
```
Then, create an object that will hold the Cross-Origin Resource Sharing (CORS) configurations. If its a storefront endpoint, pass the `origin` property storefront options:
```jsx
const corsOptions = {
origin: projectConfig.store_cors.split(","),
credentials: true,
}
```
If its an admin endpoint, pass the `origin` property admin options:
```jsx
const corsOptions = {
origin: projectConfig.admin_cors.split(","),
credentials: true,
}
```
Finally, for each route you add, create an `OPTIONS` request and add `cors` as a middleware for the route:
```jsx
router.options("/admin/hello", cors(corsOptions))
router.get("/admin/hello", cors(corsOptions), (req, res) => {
//...
})
```
## Create Multiple Endpoints
### Same File
You can add more than one endpoint in `src/api/index.js`:
```jsx
router.options("/store/hello", cors(storeCorsOptions))
router.get("/store/hello", cors(storeCorsOptions), (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
router.options("/admin/hello", cors(adminCorsOptions))
router.get("/admin/hello", cors(adminCorsOptions), (req, res) => {
res.json({
message: "Welcome to Your Admin!",
})
})
```
### Multiple Files
Alternatively, you can add multiple files for each endpoint or set of endpoints for readability and easy maintenance.
To do that with the previous example, first, create the file `src/api/store.js` with the following content:
```jsx
import cors from "cors"
import { projectConfig } from "../../../medusa-config"
export default (router) => {
const storeCorsOptions = {
origin: projectConfig.store_cors.split(","),
credentials: true,
}
router.options("/store/hello", cors(storeCorsOptions))
router.get("/store/hello", cors(storeCorsOptions), (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
}
```
You export a function that receives an Express router as a parameter and adds the endpoint `store/hello` to it.
Next, create the file `src/api/admin.js` with the following content:
```jsx
import cors from "cors"
import { projectConfig } from "../../../medusa-config"
export default (router) => {
const adminCorsOptions = {
origin: projectConfig.admin_cors.split(","),
credentials: true,
}
router.options("/admin/hello", cors(adminCorsOptions))
router.get("/admin/hello", cors(adminCorsOptions), (req, res) => {
res.json({
message: "Welcome to Your Admin!",
})
})
}
```
Again, you export a function that receives an Express router as a parameter and adds the endpoint `admin/hello` to it.
Finally, in `src/api/index.js` import the two functions at the beginning of the file:
```jsx
import storeRoutes from "./store"
import adminRoutes from "./admin"
```
and in the exported function, call each of the functions passing them the Express router:
```jsx
export default () => {
const router = Router()
storeRoutes(router)
adminRoutes(router)
return router
}
```
## Protected Routes
Protected routes are routes that should be accessible by logged-in customers or users only.
### Protect Store Routes
To make a storefront route protected, first, import the `authenticate-customer` middleware:
```jsx
import authenticate from "@medusajs/medusa/dist/api/middlewares/authenticate-customer"
```
Then, add the middleware to your route:
```jsx
router.options("/store/hello", cors(corsOptions))
router.get("/store/hello", cors(corsOptions), authenticate(), async (req, res) => {
if (req.user) {
//user is logged in
//to get customer id: req.user.customer_id
}
//...
})
```
Please note that the endpoint is still accessible by all users, however, youll be able to access the current logged-in customer if theres any.
To disallow guest customers from accessing the endpoint, you can throw an error if `req.user` is `false`.
### Protect Admin Routes
To make an admin route protected, first, import the `authenticate` middleware:
```jsx
import authenticate from "@medusajs/medusa/dist/api/middlewares/authenticate"
```
Then, add the middleware to your route:
```jsx
router.options("/admin/products/count", cors(corsOptions))
router.get("/admin/products/count", cors(corsOptions), authenticate(), (req, res) => {
//access current user
const id = req.user.userId
const userService = req.scope.resolve("userService")
const user = await userService.retrieve(id)
//...
})
```
Now, only authenticated users can access this endpoint.
## Use Services
Services in Medusa bundle a set of functionalities into one class. Then, you can use that class anywhere in your backend. For example, you can use the `ProductService` to retrieve products or perform operations like creating or updating a product.
You can retrieve any registered service in your endpoint using `req.scope.resolve` passing it the services registration name.
Heres an example of an endpoint that retrieves the count of products in your store:
```jsx
router.get("/admin/products/count", cors(corsOptions), authenticate(), (req, res) => {
const productService = req.scope.resolve("productService")
productService.count().then((count) => {
res.json({
count,
})
})
})
```
The `productService` has a `count` method that returns a Promise. This Promise resolves to the count of the products. You return a JSON of the product count.
## Building Files
Custom endpoints must be transpiled and moved to the `dist` directory. This happens when you run your server using `medusa develop` and while its running, and when you run the following command:
```bash npm2yarn
npm run build
```
## Whats Next
- Check out the available [Admin](https://docs.medusajs.com/api/admin/) and [Storefront](https://docs.medusajs.com/api/store/) APIs.
- Learn how to create a [Service](./../services/create-service.md).
@@ -190,7 +190,7 @@ medusa-plugin-custom
This guide doesn't cover how to create different files and components. If youre interested in learning how to do that, you can check out these guides:
- How to create endpoints for [storefront](../endpoints/add-storefront.md) and [admin](../endpoints/add-admin.md)
- How to [create endpoints](../endpoints/add.md)
- How to [create a service](../services/create-service.md)
- How to [create a subscriber](../subscribers/create-subscriber.md)
- How to [create an entity](./../entities/index.md)
@@ -93,4 +93,4 @@ constructor({ helloService, eventBusService }) {
## Whats Next
- Check out the [Services Reference](/references/services/classes/AuthService) to see a list of all services in Medusa.
- [Learn How to Create an Endpoint.](/advanced/backend/endpoints/add-storefront)
- [Learn How to Create an Endpoint.](../endpoints/add.md)
+1 -1
View File
@@ -60,7 +60,7 @@ Alternatively, you can build your own storefront with any frontend framework of
## Whats Next
- Customize your Medusa server by creating your own [endpoints](./advanced/backend/endpoints/add-storefront.md), [services](./advanced/backend/services/create-service.md), and [subscribers](./advanced/backend/subscribers/create-subscriber.md).
- Customize your Medusa server by creating your own [endpoints](./advanced/backend/endpoints/add.md), [services](./advanced/backend/services/create-service.md), and [subscribers](./advanced/backend/subscribers/create-subscriber.md).
- Check out guides under the Integrations section to install plugins for [CMS](./add-plugins/strapi.md), [Payment](./add-plugins/stripe.md), [Search Engines](./add-plugins/algolia.md), and more.
- Deploy your Medusa server in seconds on [Heroku](deployments/server/deploying-on-heroku.mdx), [Qovery](deployments/server/deploying-on-qovery.md), or [Digital Ocean](deployments/server/deploying-on-digital-ocean.md).
+2 -7
View File
@@ -239,13 +239,8 @@ module.exports = {
},
{
type: "doc",
id: "advanced/backend/endpoints/add-storefront",
label: "Create Endpoint for Storefront"
},
{
type: "doc",
id: "advanced/backend/endpoints/add-admin",
label: "Create Endpoint for Admin"
id: "advanced/backend/endpoints/add",
label: "Create an Endpoint"
},
{
type: "doc",