### GET API Route Example Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/api/README.md Defines a simple GET request handler for a '/store/hello-world' API route. ```typescript import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"; export async function GET(req: MedusaRequest, res: MedusaResponse) { res.json({ message: "Hello world!", }); } ``` -------------------------------- ### Example Custom CLI Script Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/scripts/README.md A basic custom CLI script that resolves the product module service and logs the count of products. It requires the Medusa container to resolve services. ```typescript import { ExecArgs, } from "@medusajs/framework/types" export default async function myScript ({ container }: ExecArgs) { const productModuleService = container.resolve("product") const [, count] = await productModuleService.listAndCountProducts() console.log(`You have ${count} product(s)`) } ``` -------------------------------- ### Multiple HTTP Method Handlers Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/api/README.md Shows how to export functions for different HTTP methods (GET, POST, PUT) within a single route file. ```typescript import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"; export async function GET(req: MedusaRequest, res: MedusaResponse) { // Handle GET requests } export async function POST(req: MedusaRequest, res: MedusaResponse) { // Handle POST requests } export async function PUT(req: MedusaRequest, res: MedusaResponse) { // Handle PUT requests } ``` -------------------------------- ### Define a Custom Scheduled Job Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/jobs/README.md Example of a custom scheduled job that resolves the product service and lists products. It includes a configuration for daily execution at midnight. ```typescript import { MedusaContainer } from "@medusajs/framework/types"; export default async function myCustomJob(container: MedusaContainer) { const productService = container.resolve("product") const products = await productService.listAndCountProducts(); // Do something with the products } export const config = { name: "daily-product-report", schedule: "0 0 * * *", // Every day at midnight }; ``` -------------------------------- ### English Translation JSON Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/admin/i18n/README.md Example of an English translation JSON file for the admin dashboard. Add language-specific JSON files to src/admin/i18n/json. ```json { "brands": { "title": "Brands", "description": "Manage your product brands" }, "done": "Done" } ``` -------------------------------- ### Execute a Workflow in an API Route Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/workflows/README.md This example demonstrates how to execute a custom workflow from within a Medusa API route. It shows how to import the workflow and run it with input data, sending the result back in the response. ```typescript import type { MedusaRequest, MedusaResponse, } from "@medusajs/framework" import myWorkflow from "../../../workflows/hello-world" export async function GET( req: MedusaRequest, res: MedusaResponse ) { const { result } = await myWorkflow(req.scope) .run({ input: { name: req.query.name as string, }, }) res.send(result) } ``` -------------------------------- ### Define a Data Model for a Module Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/modules/README.md Create a data model in TypeScript for your module's database table. This example defines a 'post' model with 'id' and 'title' fields. ```typescript import { model } from "@medusajs/framework/utils" const Post = model.define("post", { id: model.id().primaryKey(), title: model.text(), }) export default Post ``` -------------------------------- ### Run Integration Tests Source: https://github.com/medusajs/medusa-starter-default/blob/master/integration-tests/http/README.md Use medusaIntegrationTestRunner to define and execute integration tests for your Medusa API. This example shows how to test a custom GET endpoint. ```typescript import { medusaIntegrationTestRunner } from "medusa-test-utils" medusaIntegrationTestRunner({ testSuite: ({ api, getContainer }) => { describe("Custom endpoints", () => { describe("GET /store/custom", () => { it("returns correct message", async () => { const response = await api.get( `/store/custom` ) expect(response.status).toEqual(200) expect(response.data).toHaveProperty("message") expect(response.data.message).toEqual("Hello, World!") }) }) }) } }) ``` -------------------------------- ### Use Custom Module in API Route Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/modules/README.md Access and utilize your custom module's service within an API route by resolving it from the request scope. This example shows how to list posts. ```typescript import { MedusaRequest, MedusaResponse } from "@medusajs/framework" import BlogModuleService from "../../../modules/blog/service" import { BLOG_MODULE } from "../../../modules/blog" export async function GET( req: MedusaRequest, res: MedusaResponse ): Promise { const blogModuleService: BlogModuleService = req.scope.resolve( BLOG_MODULE ) const posts = await blogModuleService.listPosts() res.json({ posts }) } ``` -------------------------------- ### Configuring Middleware for API Routes Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/api/README.md Shows how to define and apply middleware functions to specific API routes using the '/api/middlewares.ts' file. Includes a sample logger middleware. ```typescript import { defineMiddlewares } from "@medusajs/framework/http" import type { MedusaRequest, MedusaResponse, MedusaNextFunction, } from "@medusajs/framework/http"; async function logger( req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction ) { console.log("Request received"); next(); } export default defineMiddlewares({ routes: [ { matcher: "/store/custom", middlewares: [logger], }, ], }) ``` -------------------------------- ### API Route with Path Parameter Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/api/README.md Demonstrates how to define an API route that accepts a dynamic path parameter, such as 'productId'. ```typescript import type { MedusaRequest, MedusaResponse, } from "@medusajs/framework/http" export async function GET(req: MedusaRequest, res: MedusaResponse) { const { productId } = req.params; res.json({ message: `You're looking for product ${productId}` }) } ``` -------------------------------- ### Generate Module Database Migrations Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/modules/README.md Use the Medusa CLI to generate database migration files for your module. This command prepares the database schema changes. ```bash npx medusa db:generate blog ``` -------------------------------- ### Create a Module Service Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/modules/README.md Define a service class for your module, extending MedusaService and including your data models. This service will handle business logic. ```typescript import { MedusaService } from "@medusajs/framework/utils" import Post from "./models/post" class BlogModuleService extends MedusaService({ Post, }){ } export default BlogModuleService ``` -------------------------------- ### Accessing Medusa Container Services Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/api/README.md Illustrates how to resolve and use Medusa services, like the product module service, from the request scope within an API route handler. ```typescript import type { MedusaRequest, MedusaResponse, } from "@medusajs/framework/http" export const GET = async ( req: MedusaRequest, res: MedusaResponse ) => { const productModuleService = req.scope.resolve("product") const [, count] = await productModuleService.listAndCount() res.json({ count, }) } ``` -------------------------------- ### Sync Module Links to Database Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/links/README.md This bash command synchronizes defined module links to the Medusa database. Ensure you have run this command after defining your links. ```bash npx medusa db:migrate ``` -------------------------------- ### Create a Product Widget Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/admin/README.md This snippet shows how to create a React component for a Medusa Admin widget. It defines the widget's content and configures its placement using `defineWidgetConfig` to appear after the product details. ```tsx import { defineWidgetConfig } from "@medusajs/admin-sdk" // The widget const ProductWidget = () => { return (

Product Widget

) } // The widget's configurations export const config = defineWidgetConfig({ zone: "product.details.after", }) export default ProductWidget ``` -------------------------------- ### Custom CLI Script with Arguments Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/scripts/README.md A custom CLI script that accepts and logs command-line arguments. Arguments are available in the `args` property of the function's parameter object. ```typescript import { ExecArgs } from "@medusajs/framework/types" export default async function myScript ({ args }: ExecArgs) { console.log(`The arguments you passed: ${args}`) } ``` -------------------------------- ### Define a Link Between Product and Blog Modules Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/links/README.md This TypeScript snippet demonstrates how to define a link between the `product` data model of the Product Module and the `post` data model of a custom Blog Module using `defineLink`. ```typescript import BlogModule from "../modules/blog" import ProductModule from "@medusajs/medusa/product" import { defineLink } from "@medusajs/framework/utils" export default defineLink( ProductModule.linkable.product, BlogModule.linkable.post ) ``` -------------------------------- ### Export Module Definition Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/modules/README.md Export the module definition from the index file, specifying the module's name and its main service. This makes the module discoverable. ```typescript import BlogModuleService from "./service" import { Module } from "@medusajs/framework/utils" export const BLOG_MODULE = "blog" export default Module(BLOG_MODULE, { service: BlogModuleService, }) ``` -------------------------------- ### Basic Product Created Subscriber Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/subscribers/README.md A simple subscriber function that logs a message when a product is created. It listens to the 'product.created' event. ```typescript import { type SubscriberConfig, } from "@medusajs/framework" // subscriber function export default async function productCreateHandler() { console.log("A product was created") } // subscriber config export const config: SubscriberConfig = { event: "product.created", } ``` -------------------------------- ### Define a Custom Workflow Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/workflows/README.md This snippet shows how to define a custom workflow using the Medusa workflows SDK. It includes creating individual steps and composing them into a complete workflow. ```typescript import { createStep, createWorkflow, WorkflowResponse, StepResponse, } from "@medusajs/framework/workflows-sdk" const step1 = createStep("step-1", async () => { return new StepResponse(`Hello from step one!`) }) type WorkflowInput = { name: string } const step2 = createStep( "step-2", async ({ name }: WorkflowInput) => { return new StepResponse(`Hello ${name} from step two!`) } ) type WorkflowOutput = { message1: string message2: string } const helloWorldWorkflow = createWorkflow( "hello-world", (input: WorkflowInput) => { const greeting1 = step1() const greeting2 = step2(input) return new WorkflowResponse({ message1: greeting1, message2: greeting2 }) } ) export default helloWorldWorkflow ``` -------------------------------- ### Configure Module in medusa-config.ts Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/modules/README.md Add your custom module to the 'modules' array in your `medusa-config.ts` file to integrate it into the Medusa application. ```typescript module.exports = defineConfig({ projectConfig: { // ... }, modules: [ { resolve: "./src/modules/blog", }, ], }) ``` -------------------------------- ### Subscriber with Event Data and Service Resolution Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/subscribers/README.md An advanced subscriber that retrieves product details using the product module service. It accesses event data and resolves services from the Medusa container. ```typescript import type { SubscriberArgs, SubscriberConfig, } from "@medusajs/framework" export default async function productCreateHandler({ event: { data }, container, }: SubscriberArgs<{ id: string }>) { const productId = data.id const productModuleService = container.resolve("product") const product = await productModuleService.retrieveProduct(productId) console.log(`The product ${product.title} was created`) } export const config: SubscriberConfig = { event: "product.created", } ``` -------------------------------- ### Export Translations in Index TS Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/admin/i18n/README.md Export your translation JSON files from src/admin/i18n/index.ts. This makes them available for use in the admin dashboard. ```typescript import en from "./json/en.json" with { type: "json" } export default { en: { translation: en, }, } ``` -------------------------------- ### Use Translations in Admin Widget Source: https://github.com/medusajs/medusa-starter-default/blob/master/src/admin/i18n/README.md Utilize the useTranslation hook from react-i18next to access translations within your admin widgets and routes. Ensure necessary UI components and SDKs are imported. ```tsx import { defineWidgetConfig } from "@medusajs/admin-sdk" import { Button, Container, Heading } from "@medusajs/ui" import { useTranslation } from "react-i18next" const ProductWidget = () => { const { t } = useTranslation() return (
{t("brands.title")}

{t("brands.description")}

) } export const config = defineWidgetConfig({ zone: "product.details.before", }) export default ProductWidget ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.