An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
How You Can Create a Custom Endpoint in a Node.js Ecommerce Platform
Medusa is an open source headless commerce platform built using Node.js. It aims to provide developers with a great experience and limitless customization capabilities.
The core of Medusa is the headless server. It exposes a set of APIs that the other 2 components, admin and storefront, can use to connect to the server and access or manipulate data.
In this tutorial, youll learn how to create custom endpoints on your Medusa server for both the storefront and admin.
Prerequisites
This tutorial assumes you already have a Medusa server installed. If not, you can follow the Quickstart guide to get started in a few minutes.
Overview
Custom endpoints reside under thesrc/api
directory in your Medusa Backend. To define a new endpoint, you can add the fileindex.js
under thesrc/api
directory. This file should export a function that returns an Express router.
Your endpoint can be under any path you wish.
Storefront Endpoint
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.
Admin Endpoint
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 insrc/api
calledindex.js
. At its basic format,index.js
should look something like this:
import { Router } from "express"export default () => { const router = Router() router.get("/hello", (req, res) => { res.json({ message: "Welcome to Your Store!", }) }) return router}
This endpoint is accessible under the path /hello
. If you want to create an endpoint for the storefront and follow Medusas conventions you can prefix the path with /store
:
router.get("/store/hello", (req, res) => {
Similarly, you can create an endpoint for the admin and follow Medusas conventions by prefixing the path with /admin
:
router.get("/admin/hello", (req, res) => {
Making Endpoints Accessible from the Admin
If youre customizing the admin dashboard or creating your own, you need to use thecors
library. AnOPTIONS
request should be added for each route and handle the requests with thecors
library.
First, you need to import your Medusas configurations along with thecors
library:
import cors from "cors"import { projectConfig } from "../../medusa-config"
Then, create an object that holds the CORS configurations:
const corsOptions = { origin: projectConfig.admin_cors.split(","), credentials: true,}
Finally, for each route you add, create anOPTIONS
request:
router.options("/admin/hello", cors(corsOptions))router.get("/admin/hello", (req, res) => { //...})
Multiple Endpoints
Same File
You can add more than one endpoints insrc/api/index.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 filesrc/api/hello.js
with the following content:
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 endpointadmin/hello
to it.
Next, create the filesrc/api/bye.js
with the following content:
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 endpointadmin/bye
to it.
Finally, insrc/api/index.js
import the two functions at the beginning of the file:
import helloRoute from "./hello"import byeRoute from "./bye"
and in the exported function, call each of the functions passing them the Express router:
export default () => { const router = Router() helloRoute(router) byeRoute(router) return router}
Use Services
Services in Medusa bundle a set of functionalities related to a model into one class. Then, you can use that class anywhere in your backend. For example, you can use theProductService
to retrieve products or perform operations like creating or updating a product.
You can retrieve any registered service in your endpoint usingreq.scope.resolve
passing it the services registration name.
Heres an example of an endpoint that retrieves the count of products in your store:
router.get("/admin/products/count", (req, res) => { const productService = req.scope.resolve("productService") productService.count().then((count) => { res.json({ count, }) })})
TheproductService
has acount
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 theauthenticate
middleware:
import authenticate from "@medusajs/medusa/dist/api/middlewares/authenticate"
Then, add the middleware to your route:
router.get("/store/products/count", authenticate(), (req, res) => { //...})
Now, only authenticated customers or users can access this endpoint.
Accessing Current Customer
You can get the logged-in customers ID usingreq.user
:
const id = req.user.customer_id
To get the customers details, you can use thecustomerService
:
const id = req.user.customer_idconst customerService = req.scope.resolve("customerService")const customer = await customerService.retrieve(id)
Accessing Current User
You can get the logged-in user ID usingreq.user
:
const id = req.user.userId
To get the users details, you can use theuserService
:
const id = req.user.userIdconst userService = req.scope.resolve("userService")const user = await userService.retrieve(id)
Route Parameters
The routes you create receive 2 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.
export default (rootDirectory, pluginOptions) => { const router = Router() //...}
Whats Next?
Endpoints are just one essential part of Medusas architecture. Here are more resources to learn more about Medusas server and how to customize it:
- What are subscribers and how to create them?
- What are services and how to create them?
- How to create a payment provider?
Should you have any issues or questions related to Medusa, then feel free to reach out to the Medusa team viaDiscord.
Original Link: https://dev.to/medusajs/how-you-can-create-a-custom-endpoint-in-a-nodejs-ecommerce-platform-4fb5
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To