AgentSkillsCN

Api Generator

一款可将 .proto 文件转换为 TypeScript 类型、React Query Hook、Express 路由以及 DTO 的代码生成工具。通过以 Protocol Buffers 作为唯一可信源,确保前后端 API 合约的一致性。运行 `npm run gen -- <package>` 即可为特定的 API 模块生成代码。

SKILL.md
--- frontmatter
description: Code generation tool that transforms .proto files into TypeScript types, React Query hooks, Express routes, and DTOs. Ensures consistent API contracts between frontend and backend by using Protocol Buffers as the single source of truth. Run `npm run gen -- <package>` to generate code for a specific API module.
category: Planning
version: 2.2

API Generator

Generate FE/BE code from .proto files.

Flow

  1. Input: bff/<pkg>/<pkg>.proto with service + google.api.http annotations
  2. Run: npm run gen -- <pkg>
  3. Output: Types, API calls, hooks, routes, DTOs

Command

bash
# Generate for a package
npm run gen -- <package_name>


# Genrate using task file
task gen -- <package_name>

Output Files

FileLocationRegenerated?
FE Typesfe/src/types/<pkg>.d.tsYes
BE Typesbe/types/<pkg>.d.tsYes
FE APIfe/src/services/<pkg>/api.tsYes
FE Hooksfe/src/services/<pkg>/useQuery.tsYes
BE Routesbe/core/api/<pkg>/<pkg>.routes.tsYes
BE DTObe/core/dto/<pkg>.dto.tsOnce only

Proto Example

protobuf
// bff/product/product.proto
syntax = "proto3";
package product;

import "google/api/annotations.proto";

service ProductService {
  rpc CreateProduct(CreateProductRequest) returns (CreateProductResponse) {
    option (google.api.http) = {
      post: "/v1/product/CreateProduct"
      body: "*"
    };
  }
  
  rpc GetProductById(GetProductByIdRequest) returns (ProductResponse) {
    option (google.api.http) = {
      get: "/v1/product/GetProductById"
    };
  }
}

message CreateProductRequest {
  string name = 1;
  string sku = 2;
}

message ProductResponse {
  string id = 1;
  string name = 2;
}

Rules

  • Proto is source of truth for API contracts
  • Never manually edit generated API/hooks/routes
  • DTO files are created once—add validation manually
  • Types are regenerated with content replacement

HTTP Methods

ProtoHTTPFE HookBE Status
postPOSTuseMutation201
getGETuseQuery200

Extending

To add PUT/PATCH/DELETE:

  1. Extend httpMethod union in generator
  2. Map google.api.http fields
  3. Adjust FE/BE writers similarly to POST logic