Medusa TSDoc 全 JSDoc 注释规范:Service 接口、JS SDK、Provider 抽象类与 Workflow SDK

原创2026-09-09 22:09:291,716 阅读
文章标签:电商后端企业应用前端流程编排认证鉴权插件系统

Medusa TSDoc 全 JSDoc 注释规范:Service 接口、JS SDK、Provider 抽象类与 Workflow SDK

本指南完整讲解 Medusa 开源仓库中四类使用完整 JSDoc 注释模式的 TypeScript 文件的文档编写规范:模块 Service 接口(packages/core/types/src/)、JS SDK 方法(packages/core/js-sdk/src/)、Provider 抽象类(packages/core/utils/src/)与 Workflow SDK 组合器函数(packages/core/workflows-sdk/src/utils/composer/)。读完本文,你将掌握这套被 Medusa 官方文档生成管线使用的注释模板,能够为自己的模块接口、SDK 方法、支付等 Provider 与工作流步骤写出格式统一、可被自动提取为 API 参考文档的 JSDoc。

概览:哪四类文件使用全 JSDoc 模式

Medusa 代码库中并非所有文件都要求完整 JSDoc,只有以下四类文件统一采用「全 JSDoc」模式(即接口/类与方法都必须具备描述、@param、@returns 与 @example):

文件类别 所在目录 典型示例
模块 Service 接口 packages/core/types/src/<module>/service.ts IProductModuleService、ICartModuleService
JS SDK 方法 packages/core/js-sdk/src/admin/、.../store/ sdk.admin.product.retrieve
Provider 抽象类 packages/core/utils/src/ AbstractPaymentProvider
Workflow SDK 组合器函数 packages/core/workflows-sdk/src/utils/composer/ createStep、createWorkflow

以上目录在仓库中均可直接验证:packages/core/types/src/ 下共有 29 个模块的 service.ts 文件(analytics、api-key、auth、cache、cart、currency、customer、file、fulfillment、index-data、inventory、link-modules、notification、order、payment、pricing、product、promotion、rbac、region、sales-channel、search、settings、stock-location、store、tax、translation、user、workflows-sdk);Workflow SDK 组合器目录 packages/core/workflows-sdk/src/utils/composer/ 下包含 create-step.ts、create-workflow.ts、create-hook.ts、transform.ts、parallelize.ts、when.ts 等组合器源码。

核心规则:全 JSDoc 模式的基本要求

无论哪一类文件,都需要遵守以下统一规则:

  • 接口/类本身:用一句话描述其用途(1-sentence description)。
  • 每个公开方法:都必须包含方法描述、@param、@returns 与 @example 四个要素。
  • JS SDK 方法:额外添加 @tags <category>,category 必须与父级 SDK 属性的 tag 模式匹配(例如 @tags products)。
  • 方法描述句式:一律以 This method [动词短语]. 开头,例如 This method retrieves a product by its ID.。
  • @param 格式:@param {Type} name - Description.,即「花括号类型 + 参数名 + 连字符 + 描述句」。
  • @returns 格式:@returns {Promise<Type>} Description of resolved value.,描述被解析后的返回值。
  • @example 格式:展示真实可运行的用法代码。

接口与类的描述写法

对于模块 Service 接口,一句话描述应以「The main service interface for the X Module.」为模板。仓库中 packages/core/types/src/product/service.ts 的真实实现即为:

/**
 * The main service interface for the Product Module.
 */
export interface IProductModuleService extends IModuleService {

对于抽象 Provider 类,描述应点明「继承此类来创建某类 Provider」的用途:

/**
 * An abstract class for payment providers. Extend this class to create a payment provider.
 */
export abstract class AbstractPaymentProvider {

在 packages/core/utils/src/payment/abstract-payment-provider.ts 中,AbstractPaymentProvider 还体现了泛型用法:AbstractPaymentProvider<TConfig>,其构造函数接收模块容器(cradle)与模块配置两个参数,官方注释建议「如果要创建客户端或与第三方服务建立连接,请在构造函数中完成」。

完整方法模式:以 retrieve 类方法为例

「检索单个实体」类方法是最典型的方法形态。完整模板如下:

/**
 * This method retrieves a product by its ID.
 *
 * @param {string} productId - The ID of the product to retrieve.
 * @param {FindConfig<ProductDTO>} config - The configurations determining how the product is retrieved. Its properties, such as `select` or `relations`, accept the attributes or relations associated with a product.
 * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
 * @returns {Promise<ProductDTO>} The retrieved product.
 *
 * @example
 * const product = await productModuleService.retrieveProduct("prod_123")
 */
retrieveProduct(
  productId: string,
  config?: FindConfig<ProductDTO>,
  sharedContext?: Context
): Promise<ProductDTO>

对照真实源码 packages/core/types/src/product/service.ts,retrieveProduct 的签名与模板完全一致。可以观察到几个要点:

  • 三个参数的顺序是固定的:主键 ID → 查询配置 config(可选)→ sharedContext(可选)。
  • config 的描述统一说明其 select、relations 等属性接受与实体关联的属性/关系名。
  • @example 只需一行可运行的调用即可,不必展示完整配置。

列表方法:可选的 filters 与多场景 @example

List 方法(listX)相比 retrieve 多了一个可选的 filters 参数,其 @example 通常拆分为多个场景。模板:

/**
 * This method retrieves a paginated list of products based on optional filters and configuration.
 *
 * @param {FilterableProductProps} filters - The filters to apply on the retrieved products.
 * @param {FindConfig<ProductDTO>} config - The configurations determining how the products are retrieved. Its properties, such as `select` or `relations`, accept the attributes or relations associated with a product.
 * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
 * @returns {Promise<ProductDTO[]>} The list of products.
 *
 * @example
 * To retrieve a list of products using their IDs:
 *
 * ```ts
 * const products = await productModuleService.listProducts({
 *   id: ["prod_123", "prod_456"],
 * })
 * ```
 *
 * To specify relations that should be retrieved:
 *
 * ```ts
 * const products = await productModuleService.listProducts(
 *   {},
 *   { relations: ["variants"] }
 * )
 * ```
 */
listProducts(
  filters?: FilterableProductProps,
  config?: FindConfig<ProductDTO>,
  sharedContext?: Context
): Promise<ProductDTO[]>

真实源码 packages/core/types/src/product/service.ts 中 listProducts 的注释结构与模板一致,且多场景 @example 会用「To retrieve ...」「To specify ...」这样的引导句为每个代码块加标签。注意 @returns 的类型是数组 ProductDTO[],与 retrieve 方法的 ProductDTO 相区分。

创建与更新方法:data 参数与批量语义

Create/Update 类方法通常接收 DTO 数组,以体现「批量创建/更新」的语义。模板:

/**
 * This method creates products.
 *
 * @param {CreateProductDTO[]} data - The products to create.
 * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
 * @returns {Promise<ProductDTO[]>} The created products.
 *
 * @example
 * const products = await productModuleService.createProducts([
 *   {
 *     title: "Shirt",
 *     options: [{ title: "Color", values: ["Blue", "Green"] }],
 *   },
 * ])
 */
createProducts(
  data: CreateProductDTO[],
  sharedContext?: Context
): Promise<ProductDTO[]>

编写要点:

  • data 参数的类型必须带数组方括号(CreateProductDTO[]),与批量语义保持一致。
  • @example 中传入真实的对象字面量,例如这里展示了嵌套的 options 结构(选项标题与可取值列表)。
  • 更新方法(如 updateProducts)遵循同样的模式,只是 DTO 换为 UpdateProductDTO,且通常还需要额外的过滤参数指定要更新的记录。

JS SDK 方法:额外添加 @tags

JS SDK 方法(如 sdk.admin.product.retrieve)在完整 JSDoc 基础上,必须追加 @tags <category>,category 与父级 SDK 属性对应:

/**
 * This method retrieves a product by its ID.
 *
 * @param {string} id - The ID of the product to retrieve.
 * @param {SelectParams} query - Configure the fields to retrieve in the product.
 * @param {RequestInit} headers - Headers to pass in the request.
 * @returns {Promise<HttpTypes.AdminProductResponse>} The product's details.
 *
 * @example
 * const product = await sdk.admin.product.retrieve("prod_123")
 *
 * @tags products
 */
async retrieve(
  id: string,
  query?: SelectParams,
  headers?: RequestInit["headers"]
): Promise<HttpTypes.AdminProductResponse> {

对照真实实现 packages/core/js-sdk/src/admin/product.ts,该方法内部通过 this.client.fetch<HttpTypes.AdminProductResponse>('/admin/products/${id}', { query, headers }) 发送 HTTP 请求,@tags products 用于把该方法归类到 SDK 的 products 模块,供文档生成器按模块聚合展示。

编写 JS SDK 方法注释时还要注意:

  • query 的类型是 SelectParams(而不是模块接口中的 FindConfig),描述应聚焦「配置要检索的字段」。
  • headers 的类型是 RequestInit["headers"]。
  • 返回类型通常是对应的 HttpTypes.Admin*Response 或 HttpTypes.Store*Response 包装类型。
  • @example 演示 sdk.admin.<resource>.<method>(...) 的调用形态。

Provider 抽象方法:面向实现的注释

Provider 抽象类的方法注释,@example 通常展示子类如何实现该抽象方法,而不是直接调用它。以支付 Provider 为例:

/**
 * This method initiates a payment session.
 *
 * @param {InitiatePaymentInput} input - The details of the payment session to initiate.
 * @returns {Promise<PaymentProviderSessionResponse>} The created payment session.
 *
 * @example
 * class MyPaymentProvider extends AbstractPaymentProvider {
 *   async initiatePayment(input) {
 *     const externalSession = await this.client.createSession(input.amount)
 *     return {
 *       id: externalSession.id,
 *       data: externalSession,
 *     }
 *   }
 * }
 */
abstract initiatePayment(
  input: InitiatePaymentInput
): Promise<PaymentProviderSessionResponse>

在 packages/core/utils/src/payment/abstract-payment-provider.ts 中,abstract initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> 是真实存在的抽象方法;其完整 @example 展示了子类 MyPaymentProviderService extends AbstractPaymentProvider<Options> 的实现方式——从 input 解构出 amount、currency_code、context,调用第三方客户端初始化支付,然后返回 { id, data } 结构。这为支付模块的插件开发者提供了「照着写」的模板。

Workflow SDK 组合器函数:文档化工作流原语

Workflow SDK 组合器(composer)函数是构建工作流的 DSL,其 JSDoc 需要解释清楚三个回调的职责。以 createStep 为例:

/**
 * Creates a new workflow step with the specified ID and handler.
 *
 * @param {string} stepId - The unique identifier for the step.
 * @param {Function} invokeFn - The function to run when the step executes.
 * @param {Function} [compensateFn] - The function to run when compensating (rolling back) the step.
 * @returns {StepFunction} The created step function.
 *
 * @example
 * const myStep = createStep(
 *   "my-step",
 *   async (input: { id: string }, { container }) => {
 *     const service = container.resolve("myService")
 *     await service.doSomething(input.id)
 *     return new StepResponse(void 0, input.id)
 *   },
 *   async (id, { container }) => {
 *     const service = container.resolve("myService")
 *     await service.undoSomething(id)
 *   }
 * )
 */
export function createStep<TInput, TOutput, TCompensateInput>(
  stepId: string,
  invokeFn: StepFunction<TInput, TOutput>,
  compensateFn?: StepFunction<TCompensateInput, void>
): ReturnType<typeof createStep>

对照 packages/core/workflows-sdk/src/utils/composer/create-step.ts 的真实签名,有几个与文档模板对应的实现细节值得注意:

  • 第一个参数实际接受 string | ({ name: string } & Omit<TransactionStepsDefinition, ...>),即既可以直接传步骤名,也可以传带 name 的步骤配置对象;内部通过 isString(nameOrConfig) ? nameOrConfig : nameOrConfig.name 解析步骤名(见 create-step.ts 中 stepName 的解析逻辑)。
  • invokeFn 必须返回 StepResponse 实例:StepResponse 构造函数第一个参数是步骤输出,第二个可选参数是传给补偿函数的数据。源码类型 InvokeFn 中 StepResponse<TOutput, TCompensateInput> 直接体现了这一点。
  • compensateFn 接收的参数是 StepResponse 构造函数的第二个参数;若未传第二个参数,则接收第一个参数(输出本身)。这一点在 create-step.ts 的 compensateFn 注释中有明确说明。
  • createStep 必须在一个 createWorkflow 定义内部调用,否则会抛出错误(create-step.ts 中检查全局 composer context,若不存在则抛出 "createStep must be used inside a createWorkflow definition")。

此外,composer 目录还包含 create-workflow.ts、create-hook.ts、transform.ts、parallelize.ts、when.ts 等组合器,它们共同构成工作流编排的 DSL 基础。

@example 多场景写法

当一个方法有多个常见用法时,不要堆砌多个无标签的代码块,而应使用引导句为每个场景加标签:

 * @example
 * A simple example that retrieves a product by its ID:
 *
 * ```ts
 * const product = await productModuleService.retrieveProduct("prod_123")
 * ```
 *
 * To specify relations that should be retrieved:
 *
 * ```ts
 * const product = await productModuleService.retrieveProduct(
 *   "prod_123",
 *   { relations: ["variants"] }
 * )
 * ```

这种写法在仓库中大量使用,例如 IProductModuleService.retrieveProduct 的真实注释就是「A simple example that retrieves a product by its ID:」与「To specify relations that should be retrieved:」两个带标签场景(见 packages/core/types/src/product/service.ts)。在真实实现中,多场景注释还会穿插 :::note 提示块(如「You can only retrieve data models defined in the same module. To retrieve linked data models from other modules, use Query instead.」),提醒读者跨模块查询应使用 Query 而非模块内检索。

sharedContext 参数的标准描述

sharedContext 参数几乎出现在所有模块 Service 方法上(也常见于 Provider 与工作流上下文),必须使用以下标准描述,保持全文措辞统一:

@param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.

该参数的类型来自 Context(定义于 packages/core/types/src/shared-context,由 @medusajs/types 导出),其作用是让调用方与应用、模块之间共享事务管理器等资源——例如在事务内调用多个模块方法时,传入同一 sharedContext 即可保证它们处于同一数据库事务中。

编写工作流:注释如何被消费

从仓库结构与工具链可以推断这套注释的消费链路:packages/core/types、packages/core/js-sdk、packages/core/utils、packages/core/workflows-sdk 均是被 packages/core/framework 聚合的底层包,@medusajs/framework/types 与 @medusajs/framework/utils 将它们的类型与实现统一导出(例如支付 Provider 示例中的 import { InitiatePaymentInput } from "@medusajs/framework/types" 与 import { AbstractPaymentProvider } from "@medusajs/framework/utils")。开发者编写的完整 JSDoc 会作为这些公开 API 的元数据,被文档生成工具与 IDE 的类型提示(IntelliSense)直接消费——统一的 @param/@returns 格式让悬停提示、自动补全与自动生成 API 参考保持一致的高质量。

快速自查清单

在提交带完整 JSDoc 的代码前,对照以下清单逐项检查:

  1. 接口/类是否有且仅有一句话描述?
  2. 每个公开方法是否都有 This method ... 开头的方法描述?
  3. 每个参数是否有 @param {Type} name - Description. 格式的注释?可选参数是否清晰标注?
  4. 每个方法是否有 @returns {Promise<Type>} Description. 注释,且返回类型(单个实体 vs 数组)与签名一致?
  5. 每个方法是否有至少一个 @example?多场景时是否用引导句加标签?
  6. JS SDK 方法是否额外添加了 @tags <category>,且与父级 SDK 属性一致?
  7. sharedContext 参数是否使用了标准描述文案?
  8. Workflow 步骤方法是否在示例中展示了 StepResponse 的构造与补偿函数的配合?

按此规范编写,即可确保你的模块接口、SDK 方法与 Provider 在 Medusa 生态中拥有与官方 API 一致的文档体验。

登录后查看全文
medusa