Chuyển đến nội dung

Bài 28 · Projects

Project: A Product Reviews Module

Build a product reviews feature for Medusa 2: a custom module, a link to Product, a workflow, store and admin routes, and a moderation flow.

Product reviews are the classic first custom feature: shoppers expect them, Medusa does not ship them, and building them touches every extension point you have learned. You will create a module that owns review data, link it to Product, write a workflow that creates a review, expose store routes for shoppers and admin routes for moderators, and add a moderation flow so nothing appears publicly before someone approves it.

The full Medusa code is shown read-only, because it needs a running Medusa project with Postgres. To make the logic tangible, two runnable stand-ins implement the same rules in plain JavaScript: a review store with a moderation workflow, and the aggregation and listing that the storefront needs.

The plan

flowchart LR
    S["Shopper<br/>POST /store/products/:id/reviews"] --> W["createReviewWorkflow"]
    W --> M["review module<br/>status: pending"]
    A["Moderator<br/>POST /admin/reviews/:id"] --> W2["moderateReviewWorkflow"]
    W2 --> M
    P["Storefront<br/>GET /store/products/:id/reviews"] --> Q["Query approved reviews"]
    M --- L["link: product to reviews"]

Writes go through workflows, reads through Query, and only approved reviews are public.

Rules we want:

  1. A review has a product, a rating from 1 to 5, a title, a body and the author's name.
  2. A new review starts as pending. Moderators set it to approved or rejected.
  3. The storefront only lists approved reviews and shows an average.
  4. One customer can review a product once.

Step 1: the data model and module

The module owns one model. Because modules never join tables across boundaries, it stores product_id as plain text; the link in step 2 connects it to the Product module for queries. See Custom Modules and Data Models for each piece (read-only code):

TypeScript
// src/modules/review/models/review.ts
import { model } from "@medusajs/framework/utils"

export const Review = model.define("review", {
  id: model.id().primaryKey(),
  product_id: model.text().index(),
  customer_id: model.text().nullable(),
  author_name: model.text(),
  rating: model.number(),
  title: model.text(),
  body: model.text(),
  status: model.enum(["pending", "approved", "rejected"]).default("pending"),
})
TypeScript
// src/modules/review/service.ts
import { MedusaService } from "@medusajs/framework/utils"
import { Review } from "./models/review"

class ReviewModuleService extends MedusaService({ Review }) {}

export default ReviewModuleService
TypeScript
// src/modules/review/index.ts
import { Module } from "@medusajs/framework/utils"
import ReviewModuleService from "./service"

export const REVIEW_MODULE = "review"

export default Module(REVIEW_MODULE, { service: ReviewModuleService })

MedusaService generates createReviews, listReviews, updateReviews, deleteReviews and friends. Register the module and generate the migration:

TypeScript
// medusa-config.ts (excerpt)
modules: [{ resolve: "./src/modules/review" }],
Terminal
npx medusa db:generate review
npx medusa db:migrate

A link lets Query return a product with its reviews without the two modules knowing each other (Module Links):

TypeScript
// src/links/product-review.ts
import { defineLink } from "@medusajs/framework/utils"
import ProductModule from "@medusajs/medusa/product"
import ReviewModule from "../modules/review"

export default defineLink(
  ProductModule.linkable.product,
  { linkable: ReviewModule.linkable.review, isList: true }
)

After npx medusa db:migrate, query.graph({ entity: "product", fields: ["id", "title", "review.*"] }) can return reviews next to products. For the public list we will query the review module directly with a status filter, which is simpler and indexed by product_id.

Step 3: the workflow

Creating a review is one write today, but putting it in a workflow gives you validation in one place, a compensation function and an obvious home for later steps such as "notify moderators" or "award loyalty points" (Workflows and Steps).

TypeScript
// src/workflows/create-review.ts
import {
  createStep,
  createWorkflow,
  StepResponse,
  WorkflowResponse,
} from "@medusajs/framework/workflows-sdk"
import { MedusaError } from "@medusajs/framework/utils"
import { REVIEW_MODULE } from "../modules/review"
import ReviewModuleService from "../modules/review/service"

type Input = {
  product_id: string
  customer_id: string
  author_name: string
  rating: number
  title: string
  body: string
}

const assertNoDuplicateStep = createStep(
  "assert-no-duplicate-review",
  async (input: Input, { container }) => {
    const service: ReviewModuleService = container.resolve(REVIEW_MODULE)
    const existing = await service.listReviews({
      product_id: input.product_id,
      customer_id: input.customer_id,
    })
    if (existing.length > 0) {
      throw new MedusaError(
        MedusaError.Types.NOT_ALLOWED,
        "You have already reviewed this product"
      )
    }
    return new StepResponse(input)
  }
)

const createReviewStep = createStep(
  "create-review",
  async (input: Input, { container }) => {
    const service: ReviewModuleService = container.resolve(REVIEW_MODULE)
    const review = await service.createReviews({ ...input, status: "pending" })
    return new StepResponse(review, review.id)
  },
  async (reviewId, { container }) => {
    if (!reviewId) return
    const service: ReviewModuleService = container.resolve(REVIEW_MODULE)
    await service.deleteReviews(reviewId)
  }
)

export const createReviewWorkflow = createWorkflow(
  "create-review",
  (input: Input) => {
    const checked = assertNoDuplicateStep(input)
    const review = createReviewStep(checked)
    return new WorkflowResponse(review)
  }
)

A matching moderateReviewWorkflow has one step that calls updateReviews({ id, status }) after checking the transition is allowed, with a compensation that restores the old status.

Step 4: store and admin routes

Request bodies are validated with Zod and attached through defineMiddlewares (Custom API Routes and Middleware). The shopper route needs a logged-in customer:

TypeScript
// src/api/store/products/[id]/reviews/route.ts
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { REVIEW_MODULE } from "../../../../../modules/review"
import { createReviewWorkflow } from "../../../../../workflows/create-review"

export async function GET(req: MedusaRequest, res: MedusaResponse) {
  const service = req.scope.resolve(REVIEW_MODULE)
  const reviews = await service.listReviews(
    { product_id: req.params.id, status: "approved" },
    { order: { created_at: "DESC" }, take: 20 }
  )
  res.json({ reviews })
}

export async function POST(req: MedusaRequest, res: MedusaResponse) {
  const { result } = await createReviewWorkflow(req.scope).run({
    input: {
      ...(req.validatedBody as any),
      product_id: req.params.id,
      customer_id: req.auth_context.actor_id, // never trust a body field
    },
  })
  res.status(201).json({ review: result })
}
TypeScript
// src/api/admin/reviews/[id]/route.ts  (moderators)
export async function POST(req: MedusaRequest, res: MedusaResponse) {
  const { result } = await moderateReviewWorkflow(req.scope).run({
    input: { id: req.params.id, status: (req.validatedBody as any).status },
  })
  res.json({ review: result })
}

The middleware file marks /store/products/*/reviews POST as customer-authenticated, validates the body with a Zod schema (rating 1 to 5, non-empty title) and protects the admin route with admin authentication. An admin dashboard widget or UI route can list pending reviews (Admin Dashboard Extensions).

Stand-in 1: the moderation workflow

This stand-in implements the same rules without a database: duplicate check, validation, a pending start, controlled status transitions and a compensating undo. Run it to see each rule fire.

JS A review store with a moderation workflow

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in 2: what the storefront reads

The public endpoint lists only approved reviews, newest first with a page size, and the product page shows an average and a star histogram. These are exactly the numbers you would cache (Security and Performance) and invalidate when a moderator approves a review.

JS Public listing, average and histogram

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that rejected and pending reviews are invisible to the public numbers, and that an empty product returns average: null rather than dividing by zero.

Extending the project

  • Add verified_purchase by checking the customer has an order containing the product (query the Order module through a link).
  • Emit a review.created event from the workflow and send a moderator email from a subscriber (Events and Subscribers).
  • Show pending counts on an admin widget.
  • Add rate limiting on the POST route and store the average on the product's metadata if you need it in search results.
  • Write tests: a workflow test for the duplicate rule and for compensation (Testing Modules, Workflows and APIs).

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Why does the review model store product_id as text instead of a foreign key to the product table?

    Medusa modules own their own tables. Cross-module relationships are expressed with module links and read with Query, not with database foreign keys.
  2. 2. Where should the customer id for a new review come from?

    A body field can be forged. The authenticated actor id is established by the auth middleware and cannot be chosen by the caller.
  3. 3. What status does a newly created review have, and who changes it?

    Reviews start as pending and only appear publicly after a moderator approves them through the admin route.
  4. 4. What does the compensation function of the create-review step do?

    The compensation receives what the step returned for rollback, here the review id, and deletes the record so a failed workflow leaves no half-finished data.
  5. 5. In the stand-in, why does summary() return average null for a product with no approved reviews?

    With zero approved reviews there is no meaningful average. Returning null lets the page hide the rating instead of showing NaN.

Summary

  • A reviews feature is one module (model, service, registration), one link to Product, workflows for writes and routes for access.
  • Reviews start pending; only approved ones are listed publicly, and status changes follow allowed transitions.
  • Take the customer id from the authenticated actor, validate bodies with Zod and keep one-review-per-customer in the workflow.
  • Give create steps a compensation function so failures leave no stray rows.
  • Aggregates such as the average and histogram are cacheable and must be invalidated on moderation.
  • The runnable code is a stand-in for the rules; the Medusa code needs a real project and database.

Next: Project: A Loyalty Points Program

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.