热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
解析用户需求并生成多技术栈项目框架,包含目录结构、初始化代码及配置文件,支持代码优化与重构,提升开发效率和项目工程化质量。
{
"response": "已解析需求并为“SaaS多租门户”提供可维护性优先的 TypeScript Monorepo 项目框架(TurboRepo),覆盖前端 Next.js、后端 NestJS + Prisma、PostgreSQL、Redis、RabbitMQ、REST/GraphQL、JWT+OIDC、OpenAPI/GraphQL 文档、OpenTelemetry+Prometheus 观测、Docker/K8s、统一工程规范与代码生成器。关键设计与初始化要点:\n\n一、模块边界与分层(可维护性优先)\n- 后端分层:modules(业务) / libs(基础设施) / interfaces(REST/GraphQL) / core(跨域能力)\n - 核心域:identity(用户/认证/授权)、tenancy(租户/成员/隔离)、billing(订阅/计划/计费)、audit(审计日志)、support(工单)、notify(通知)\n - 基础设施:prisma(数据库访问)、cache(redis)、mq(rabbitmq)、observability(otel/prometheus/logging)、config(配置)、security(rbac/policies)\n - 接口层:rest(controllers + DTO)、graphql(resolvers + schema)\n - 跨域:error handling、logging、tracing、transaction boundary、idempotency\n- 前端分层:app(Next App Router) / features(按域切片) / shared(ui/hooks/lib) / state(zustand stores)\n - SSR/CSR 按路由与运行时切换;i18n 基于 next-intl\n- 插件化扩展点:\n - 后端:PluginRegistry(packages/shared-plugin-api)定义 IPlugin 接口(注册 GraphQL/REST、订阅队列、数据迁移、RBAC 策略)。AppModule 在启动时动态发现 packages/plugins/* 并注册。\n - 前端:Feature 插件(暴露路由段、导航项、Zustand slice、权限守卫),通过 manifest 声明并动态装载。\n\n二、关键工程化\n- Monorepo:turbo + pnpm 工作区;统一 ESLint/Prettier/TSConfig;生成脚本:codegen(OpenAPI/GraphQL/Prisma)、plop/自定义 CLI 脚手架。\n- CI/CD:GitHub Actions(build/test/lint/graph gen/docker build&push/k8s 部署),利用 turbo cache。\n- 测试:Jest 单元测试,Playwright 端到端(前端),SuperTest(后端 REST),GraphQL e2e。\n- 观测:OpenTelemetry NodeSDK(OTLP 到 Collector),Prometheus metrics(/metrics),日志:pino,多租户字段入日志与 trace attributes。\n\n三、SSR/CSR 切换策略(Next.js)\n- 默认 SSR:路由级配置(在页面中使用 export const dynamic = 'force-dynamic')。CSR 路由通过 'use client' + SWR/Zustand 获取数据。\n- 环境/用户偏好切换:读取 cookie/x-header 以强制 CSR(降级模式应对后端压力)。\n\n四、初始化代码与配置(核心片段)\n1) 后端 main.ts(Nest 启动 + Swagger + GraphQL + OTel + Prometheus)\n"use strict";\nimport { NestFactory } from "@nestjs/core";\nimport { AppModule } from "./app.module";\nimport { ValidationPipe } from "@nestjs/common";\nimport { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";\nimport { Logger } from "@nestjs/common";\nimport { setupTracing } from "./observability/otel";\nimport { PrometheusMiddleware } from "./observability/prometheus";\n\nasync function bootstrap() {\n await setupTracing();\n const app = await NestFactory.create(AppModule, { bufferLogs: true });\n app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));\n app.use(PrometheusMiddleware);\n app.setGlobalPrefix("/api");\n\n const config = new DocumentBuilder()\n .setTitle("SaaS Portal API")\n .setVersion("1.0")\n .addBearerAuth()\n .build();\n const document = SwaggerModule.createDocument(app, config);\n SwaggerModule.setup("/docs", app, document);\n\n await app.listen(process.env.PORT || 3001);\n Logger.log(API listening on ${await app.getUrl()});\n}\nbootstrap();\n\n2) AppModule(配置 Redis/RabbitMQ/GraphQL/Prisma/Throttler)\nimports: [\n ConfigModule.forRoot({ isGlobal: true, envFilePath: [.env.local, .env] }),\n CacheModule.register({ isGlobal: true, store: redisStore, url: process.env.REDIS_URL }),\n RabbitMQModule.forRoot(RabbitMQModule, { exchanges: [{ name: "events", type: "topic" }], uri: process.env.RABBITMQ_URL }),\n ThrottlerModule.forRoot([{ ttl: 60000, limit: 120 }]),\n GraphQLModule.forRootAudit: ${entry.event});\n return this.prisma.auditLog.create({ data: { event: entry.event, userId: entry.userId ?? undefined, tenantId: entry.tenantId ?? undefined, data: entry.data ?? {}, ip: entry.ip, userAgent: entry.ua } });\n }\n}\n\n// apps/backend/src/modules/identity/auth.module.ts\nimport { Module } from '@nestjs/common';\nimport { JwtModule } from '@nestjs/jwt';\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\nimport { AuditService } from '../audit/audit.service';\nimport { PrismaService } from '../../libs/prisma/prisma.service';\n\n@Module({\n imports: [JwtModule.register({})],\n controllers: [AuthController],\n providers: [AuthService, AuditService, PrismaService],\n})\nexport class AuthModule {}\n",
"project_structure": [
"SaaS多租门户/",
"├─ apps/",
"│ ├─ backend/ (NestJS + Prisma)",
"│ │ ├─ src/",
"│ │ │ ├─ main.ts",
"│ │ │ ├─ app.module.ts",
"│ │ │ ├─ interfaces/",
"│ │ │ │ ├─ rest/",
"│ │ │ │ │ └─ (controllers wired in each module)",
"│ │ │ │ └─ graphql/",
"│ │ │ │ └─ (resolvers/schema code-first)",
"│ │ │ ├─ core/",
"│ │ │ │ ├─ filters/http-exception.filter.ts",
"│ │ │ │ ├─ interceptors/tenant-context.interceptor.ts",
"│ │ │ │ └─ guards/rbac.guard.ts",
"│ │ │ ├─ libs/",
"│ │ │ │ ├─ prisma/",
"│ │ │ │ │ ├─ prisma.service.ts",
"│ │ │ │ │ └─ prisma.module.ts",
"│ │ │ │ ├─ mq/rabbitmq.module.ts",
"│ │ │ │ ├─ cache/redis.module.ts",
"│ │ │ │ └─ config/config.module.ts",
"│ │ │ ├─ observability/",
"│ │ │ │ ├─ otel.ts (OpenTelemetry NodeSDK bootstrap)",
"│ │ │ │ ├─ logger.ts (pino logger with tenant/user enrich)",
"│ │ │ │ └─ prometheus.ts (metrics middleware + /metrics)",
"│ │ │ ├─ modules/",
"│ │ │ │ ├─ identity/ (注册/登录/JWT/OIDC/RBAC)",
"│ │ │ │ │ ├─ auth.controller.ts",
"│ │ │ │ │ ├─ auth.service.ts",
"│ │ │ │ │ ├─ auth.module.ts",
"│ │ │ │ │ ├─ dto/login.dto.ts",
"│ │ │ │ │ ├─ jwt.strategy.ts",
"│ │ │ │ │ ├─ oidc.strategy.ts (open id connect via openid-client)",
"│ │ │ │ │ └─ rbac.policies.ts",
"│ │ │ │ ├─ tenancy/ (租户/成员/隔离)",
"│ │ │ │ │ ├─ tenancy.controller.ts",
"│ │ │ │ │ ├─ tenancy.service.ts",
"│ │ │ │ │ └─ tenancy.module.ts",
"│ │ │ │ ├─ billing/ (订阅管理/计划/计费webhook)",
"│ │ │ │ ├─ audit/ (审计日志)",
"│ │ │ │ ├─ support/ (工单)",
"│ │ │ │ └─ notify/ (通知中心/队列消费者)",
"│ │ │ └─ graphql.ts (GraphQL module config - code-first)",
"│ │ ├─ prisma/",
"│ │ │ ├─ schema.prisma",
"│ │ │ ├─ migrations/",
"│ │ │ └─ seed.ts",
"│ │ ├─ test/",
"│ │ │ ├─ auth.e2e.spec.ts",
"│ │ │ └─ tenancy.spec.ts",
"│ │ ├─ jest.config.ts",
"│ │ ├─ Dockerfile",
"│ │ └─ tsconfig.json",
"│ └─ frontend/ (Next.js + Zustand + Tailwind)",
"│ ├─ app/",
"│ │ ├─ layout.tsx",
"│ │ ├─ page.tsx",
"│ │ ├─ (auth)/login/page.tsx",
"│ │ ├─ (tenant)/dashboard/page.tsx",
"│ │ └─ api/ (route handlers if needed)",
"│ ├─ features/",
"│ │ ├─ identity/",
"│ │ ├─ tenancy/",
"│ │ ├─ billing/",
"│ │ ├─ audit/",
"│ │ └─ notify/",
"│ ├─ state/",
"│ │ ├─ auth.store.ts",
"│ │ └─ ui.store.ts",
"│ ├─ components/",
"│ │ ├─ ui/",
"│ │ └─ charts/",
"│ ├─ lib/",
"│ │ ├─ api-client.ts (OpenAPI/GraphQL clients)",
"│ │ ├─ i18n.ts",
"│ │ └─ ssr-csr.ts (render mode toggle helpers)",
"│ ├─ public/",
"│ ├─ styles/",
"│ │ └─ globals.css",
"│ ├─ next.config.js",
"│ ├─ tailwind.config.js",
"│ ├─ postcss.config.js",
"│ ├─ playwright.config.ts",
"│ ├─ Dockerfile",
"│ └─ tsconfig.json",
"├─ packages/",
"│ ├─ shared/ (types/utils)",
"│ │ ├─ src/",
"│ │ │ ├─ index.ts",
"│ │ │ ├─ domain/ (shared domain types, errors, result)",
"│ │ │ └─ utils/",
"│ │ └─ tsconfig.json",
"│ ├─ shared-plugin-api/ (后端插件接口定义)",
"│ │ └─ src/index.ts",
"│ ├─ generated/",
"│ │ ├─ graphql.ts (graphql-codegen 输出)",
"│ │ └─ openapi.ts (openapi-typescript 输出)",
"│ ├─ eslint-config/",
"│ │ └─ index.js",
"│ ├─ tsconfig/ (base tsconfigs)",
"│ │ ├─ base.json",
"│ │ └─ nest.json",
"│ └─ codegen/ (脚手架与生成器)",
"│ ├─ scaffold.ts (约定式模块生成器)",
"│ └─ README.md",
"├─ infra/",
"│ ├─ docker/",
"│ │ ├─ docker-compose.yml (postgres/redis/rabbitmq/otel-collector/prometheus/grafana)",
"│ │ └─ init/ (db init scripts)",
"│ ├─ k8s/",
"│ │ ├─ namespace.yaml",
"│ │ ├─ backend-deploy.yaml",
"│ │ ├─ backend-svc.yaml",
"│ │ ├─ frontend-deploy.yaml",
"│ │ ├─ frontend-svc.yaml",
"│ │ ├─ ingress.yaml",
"│ │ ├─ configmap.yaml",
"│ │ ├─ secret.yaml",
"│ │ ├─ hpa.yaml",
"│ │ └─ servicemonitor.yaml",
"│ ├─ telemetry/",
"│ │ ├─ otel-collector-config.yaml",
"│ │ └─ prometheus.yaml",
"│ └─ ci/",
"│ └─ github-actions/",
"│ └─ ci.yml",
"├─ graphql-codegen.yaml",
"├─ openapi.config.json",
"├─ turbo.json",
"├─ pnpm-workspace.yaml",
"├─ package.json",
"├─ .eslintrc.js",
"├─ .prettierrc",
"├─ .env.example",
"├─ README.md (启动/部署/约定/扩展点说明)",
"└─ CONTRIBUTING.md (提交规范/代码风格/分支策略/Release 说明)"
]
}
{ "response": "需求解析与设计结论:\n- 项目目标:实时数据枢纽平台,支持多源接入、清洗、指标汇总与可视化。性能优先,强调批量写入、异步IO、缓存、消息压缩、分区与并行度调优。\n- 技术栈:Python(FastAPI + SQLAlchemy 2.x Async)、Kafka、Redis、PostgreSQL、Celery、OpenTelemetry、PyTest + Playwright、Docker Compose、Helm、前端 Vue3 + Vite + ECharts、数据格式 Parquet。\n- 目录结构:frontend、api、ingestion、jobs、infra。初始化模块:数据源管理、主题/分区配置、ETL模板、指标模型与维表。配置:Kafka、Redis、PostgreSQL、对象存储(MinIO/S3)、权限策略、环境变量模板。工程化:代码规范、单元/集成测试、性能基准、容器化与部署脚本、指标与日志采集。\n\n关键架构与优化策略:\n1) 后端(FastAPI):\n- 使用 SQLAlchemy Async + 单次批量查询(IN 查询),避免 N+1。\n- CPU 密集计算通过 ProcessPoolExecutor 并行化,避免 GIL 限制;如超大批次通过 Celery 异步离线计算。\n- Redis 缓存:MGET 批量读取、Pipeline 批量写入、TTL 与版本号做失效管理。\n- OpenTelemetry:HTTP、DB、Redis、Kafka 自动/手动埋点,OTLP 输出到 Collector。\n- 指标与日志:Prometheus FastAPI exporter 或 OTEL Metric,JSON 结构化日志。\n\n2) 消息与调度:\n- Kafka 生产与消费使用压缩(zstd),在分区上按业务键(如用户/主题)做分区,提高局部性与并行度。\n- 消费者使用 aiokafka 异步消费 + 幂等写入(基于业务键 + 去重表/Redis 短期去重)。\n- 死信队列:主题 xxx.dlq,配合重试策略(指数退避、最大重试次数)。\n- Celery:任务用于离线批计算与补偿任务(任务幂等:task_id+参数签名)。\n\n3) 数据层:\n- PostgreSQL:分区表(按日期/业务键),批量写入(executemany + COPY)、索引优化(组合索引)。\n- 对象存储:Parquet 数据湖(MinIO 本地,S3 生产),ETL 模板将原始数据清洗后落 Parquet 并建 Delta 目录结构。\n\n4) 前端:\n- Vue3 + Vite + ECharts:仪表盘、图表与查询面板;Playwright 端到端测试;支持深链接与筛选参数。\n\n5) 工程化:\n- 代码规范:Black、isort、Flake8、mypy(可选);pre-commit 钩子。\n- 测试:PyTest(unit/integration),Playwright(frontend),pytest-benchmark(性能基准)。\n- 容器化:Docker Compose(本地),Helm(生产);OTEL Collector、Prometheus、Grafana。\n\n初始化代码与配置要点(摘要):\n- api/app/config.py:集中读取环境变量(Postgres、Redis、Kafka、S3/MinIO、OTLP)。\n- api/app/tracing.py:OpenTelemetry FastAPI Instrumentation + OTLP exporter。\n- api/app/models:指标模型与维表,如 Metric, Dimension, MetricFact;维表(TimeDim, UserDim, SourceDim)。\n- ingestion/consumers/kafka_consumer.py:aiokafka 消费、幂等、重试与 DLQ。\n- ingestion/pipelines/etl_template.py:读取多源,清洗,写入 Parquet(pyarrow + fastparquet),并可触发下游指标计算。\n- jobs/celery_app.py:Celery 配置 broker=Redis/Kafka(推荐 Redis)+ backend=Redis;OpenTelemetry 集成。\n- infra/configs/kafka/topics.yaml:主题与分区配置(生产建议 12-48 分区,根据吞吐与消费者数调优),压缩 zstd。\n- infra/docker-compose.yml:包含 api、ingestion、jobs(worker+beat)、postgres、redis、kafka+zookeeper、minio、otel-collector、prometheus、grafana、frontend。\n- infra/env/.env.example:环境变量模板(见下)。\n\n示例环境变量模板(摘录):\nPOSTGRES_DSN=postgresql+asyncpg://hub:hub@postgres:5432/hub\nREDIS_URL=redis://redis:6379/0\nKAFKA_BOOTSTRAP_SERVERS=kafka:9092\nKAFKA_COMPRESSION=zstd\nS3_ENDPOINT=http://minio:9000\nS3_ACCESS_KEY=minioadmin\nS3_SECRET_KEY=minioadmin\nS3_BUCKET=hub-raw\nOTLP_ENDPOINT=http://otel-collector:4317\nCELERY_BROKER_URL=redis://redis:6379/1\nCELERY_RESULT_BACKEND=redis://redis:6379/2\n\n权限策略:\n- RBAC:roles={admin, analyst, viewer};基于路由声明权限,资源粒度到数据源与主题。策略文件 infra/configs/auth/policy.json。\n\n开发指南(快速开始):\n1) 克隆与初始化:\n- 填写 infra/env/.env(复制 .env.example)。\n- 安装 pre-commit:pre-commit install。\n2) 本地启动:\n- docker compose up -d(首次会初始化 Postgres/Redis/Kafka/MinIO/OTEL)。\n- 前端:cd frontend && pnpm i && pnpm dev。\n3) 数据示例与字典:\n- 运行 infra/scripts/load_sample_data.py 导入样例数据集到 MinIO/Parquet 与 Postgres 维表。\n- data/dictionary.md 提供字段含义、业务口径与指标定义。\n4) 测试与基准:\n- 后端:pytest;性能:pytest -k benchmark。\n- 前端:pnpm test:e2e(Playwright)。\n5) 部署生产:\n- Helm:helm install data-hub infra/helm -f infra/helm/values.yaml。\n- 配置 Kafka ACL、Prometheus 抓取、Grafana dashboard 导入。\n\n性能调优默认值:\n- Kafka:compression.type=zstd;acks=all;linger.ms=50;batch.size=256KB;max.in.flight.requests.per.connection=1(保证顺序)。\n- Redis:合理 TTL;Pipeline 批量写;热点键加随机后缀防击穿;BloomFilter/Set 去重(可选)。\n- DB:连接池大小=CPU*2;prepared statements;COPY 批导;维表用主键+必要索引。\n- 并行:ProcessPoolExecutor(max_workers=os.cpu_count());消费者并行度=分区数;避免过度切分导致上下文切换开销。\n", "optimized_code": "from typing import List, Dict, Any\nimport os\nimport asyncio\nfrom fastapi import APIRouter, Depends, Query, HTTPException\nfrom pydantic import BaseModel\nfrom sqlalchemy import select\nfrom sqlalchemy.orm import load_only\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom concurrent.futures import ProcessPoolExecutor\n\n# ---- Dependencies & placeholders (wire these in your app) ----\n# Provide actual implementations in api/app/deps.py\nasync def get_session() -> AsyncSession: ...\nasync def get_redis() -> "Redis": ... # aioredis client\n\n# ORM model and CPU-heavy compute function\nclass Model: # SQLAlchemy ORM mapped class\n id: int\n a: float\n b: float\n\n# Example CPU-heavy function (must be pure & picklable)\ndef compute(a: float, b: float) -> float:\n # Simulate expensive calculation\n return (a ** 2 + b ** 2) ** 0.5\n\n# Batch compute helper to minimize IPC overhead\ndef compute_many(payloads: List[Dict[str, Any]]) -> Dict[int, float]:\n return {p["id"]: compute(p["a"], p["b"]) for p in payloads}\n\nclass MetricOut(BaseModel):\n id: int\n value: float\n\nrouter = APIRouter()\n\nCACHE_TTL_SECONDS = 300\n\n@router.get("/metrics", response_model=List[MetricOut])\nasync def metrics(\n ids: List[int] = Query(..., description="Metric IDs to compute"),\n session: AsyncSession = Depends(get_session),\n redis = Depends(get_redis),\n):\n if not ids:\n raise HTTPException(status_code=400, detail="ids cannot be empty")\n\n # 1) Batch cache lookup\n keys = [f"metric:v1:{i}" for i in ids]\n cached_vals = await redis.mget(keys)\n cache_hit: Dict[int, float] = {}\n missing_ids: List[int] = []\n for i, raw in zip(ids, cached_vals):\n if raw is not None:\n try:\n cache_hit[i] = float(raw)\n except ValueError:\n missing_ids.append(i)\n else:\n missing_ids.append(i)\n\n # 2) Single DB batch query for missing ids\n payloads: List[Dict[str, Any]] = []\n if missing_ids:\n result = await session.execute(\n select(Model)\n .options(load_only(Model.id, Model.a, Model.b))\n .where(Model.id.in_(missing_ids))\n )\n items: List[Model] = result.scalars().all()\n if len(items) != len(missing_ids):\n found_ids = {m.id for m in items}\n not_found = [mid for mid in missing_ids if mid not in found_ids]\n if not_found:\n # Soft-fail the missing ids; you may choose to 404 instead\n missing_ids = [mid for mid in missing_ids if mid in found_ids]\n payloads = [{"id": m.id, "a": m.a, "b": m.b} for m in items]\n\n # 3) Parallel CPU compute in process pool (avoid GIL)\n computed: Dict[int, float] = {}\n if payloads:\n loop = asyncio.get_running_loop()\n # Use a shared executor; in production create it once per app\n with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor:\n computed = await loop.run_in_executor(executor, compute_many, payloads)\n\n # 4) Batch cache set with pipeline\n pipe = redis.pipeline()\n for mid, val in computed.items():\n pipe.set(f"metric:v1:{mid}", val, ex=CACHE_TTL_SECONDS)\n await pipe.execute()\n\n # 5) Assemble response preserving input order\n values: Dict[int, float] = {**cache_hit, **computed}\n rows = [MetricOut(id=i, value=values[i]) for i in ids if i in values]\n\n return rows\n", "project_structure": [ "数据枢纽平台/", "├── frontend/", "│ ├── src/", "│ │ ├── main.ts", "│ │ ├── App.vue", "│ │ ├── pages/", "│ │ │ ├── Dashboard.vue", "│ │ │ └── QueryPanel.vue", "│ │ ├── components/", "│ │ │ ├── charts/", "│ │ │ │ ├── MetricLine.vue", "│ │ │ │ └── TopKBar.vue", "│ │ │ └── layout/", "│ │ │ └── PageShell.vue", "│ │ ├── services/", "│ │ │ └── api.ts", "│ │ └── router/", "│ │ └── index.ts", "│ ├── vite.config.ts", "│ ├── package.json", "│ ├── tsconfig.json", "│ └── tests/", "│ └── e2e/", "│ ├── playwright.config.ts", "│ └── dashboard.spec.ts", "├── api/", "│ ├── app/", "│ │ ├── main.py", "│ │ ├── config.py", "│ │ ├── deps.py", "│ │ ├── tracing.py", "│ │ ├── logging.py", "│ │ ├── routers/", "│ │ │ ├── metrics.py", "│ │ │ ├── datasources.py", "│ │ │ ├── topics.py", "│ │ │ └── auth.py", "│ │ ├── models/", "│ │ │ ├── base.py", "│ │ │ ├── dimension.py", "│ │ │ └── metric.py", "│ │ ├── schemas/", "│ │ │ ├── metric.py", "│ │ │ └── datasource.py", "│ │ ├── services/", "│ │ │ ├── cache.py", "│ │ │ ├── compute.py", "│ │ │ ├── storage.py", "│ │ │ └── kafka_producer.py", "│ │ ├── auth/", "│ │ │ ├── rbac.py", "│ │ │ └── policy_loader.py", "│ │ ├── tests/", "│ │ │ ├── unit/", "│ │ │ │ └── test_metrics.py", "│ │ │ └── integration/", "│ │ │ └── test_api_integration.py", "│ │ └── alembic/", "│ │ ├── env.py", "│ │ ├── script.py.mako", "│ │ └── versions/", "│ ├── pyproject.toml", "│ ├── requirements.txt", "│ └── pre-commit-config.yaml", "├── ingestion/", "│ ├── consumers/", "│ │ ├── kafka_consumer.py", "│ │ └── dlq_handler.py", "│ ├── pipelines/", "│ │ ├── etl_template.py", "│ │ └── parquet_writer.py", "│ ├── schemas/", "│ │ └── datasource.json", "│ └── tests/", "│ └── test_ingestion.py", "├── jobs/", "│ ├── celery_app.py", "│ ├── tasks/", "│ │ ├── metrics.py", "│ │ └── housekeeping.py", "│ └── schedules/", "│ └── beat_schedule.py", "├── infra/", "│ ├── docker-compose.yml", "│ ├── helm/", "│ │ ├── Chart.yaml", "│ │ ├── values.yaml", "│ │ └── templates/", "│ │ ├── deployment-api.yaml", "│ │ ├── deployment-ingestion.yaml", "│ │ ├── deployment-jobs.yaml", "│ │ ├── service-api.yaml", "│ │ └── configmap-env.yaml", "│ ├── k8s/", "│ │ ├── api-deployment.yaml", "│ │ └── otel-collector.yaml", "│ ├── configs/", "│ │ ├── kafka/", "│ │ │ ├── topics.yaml", "│ │ │ └── client.properties", "│ │ ├── postgres/", "│ │ │ └── init.sql", "│ │ ├── redis/", "│ │ │ └── redis.conf", "│ │ ├── auth/", "│ │ │ └── policy.json", "│ │ ├── otel/", "│ │ │ └── collector-config.yaml", "│ │ └── grafana/", "│ │ └── dashboards/", "│ │ └── hub-overview.json", "│ ├── env/", "│ │ └── .env.example", "│ ├── scripts/", "│ │ ├── init.sh", "│ │ ├── load_sample_data.py", "│ │ └── benchmark_metrics.py", "│ └── Makefile", "├── data/", "│ ├── sample/", "│ │ ├── sources.csv", "│ │ └── metrics.parquet", "│ └── dictionary.md", "└── README.md" ] }
{
"response": "已解析需求并为“移动零售套件”生成与 Go + Flutter 技术栈匹配的项目框架,优先保证快速开发。整体采用前后端分域分层与可观测性内建:移动端 Flutter + Riverpod 离线优先、主题切换;后端采用 Gin + GORM + REST,MySQL/Redis/Meilisearch/NATS,JWT 认证,OpenTelemetry + Prometheus。工程化包含统一代码规范、脚手架、测试、CI、Docker 镜像与 K8s 部署。关键设计建议:1) 领域分层:gateway(BFF/认证/聚合) + services(订单/库存/支付/用户) + infra(配置/部署/数据);2) 状态管理约束:Riverpod ReadOnly/Notifier 分层,离线队列与缓存隔离(core/storage),网络状态与合并策略独立(core/sync);3) 幂等:服务端以 Idempotency-Key + 请求哈希表 + 唯一索引保证订单创建幂等;4) 离线数据合并:客户端维护操作队列与版本戳,采用“服务器权威 + 客户端补偿”策略,冲突时按字段级合并与重试;5) 可观测性:Gin/GORM 接入 OTel tracing,NATS 消费与接口指标暴露到 Prometheus,并在 mobile 埋点登录、下单、同步时序。以下提供项目结构、后端初始化与移动端初始化示例,以及优化后的订单创建代码。",
"optimized_code": "package order\n\nimport (\n "crypto/sha256"\n "encoding/hex"\n "encoding/json"\n "errors"\n "net/http"\n "time"\n\n "github.com/gin-gonic/gin"\n "github.com/google/uuid"\n "gorm.io/gorm"\n)\n\n// Models\ntype Order struct {\n ID string gorm:\"primaryKey;size:36\" json:\"id\"\n StoreID string gorm:\"index;size:36\" json:\"store_id\"\n UserID string gorm:\"index;size:36\" json:\"user_id\"\n Status string gorm:\"index;size:16\" json:\"status\"\n TotalCents int64 json:\"total_cents\"\n Items []OrderItem gorm:\"foreignKey:OrderID\" json:\"items\"\n CreatedAt time.Time json:\"created_at\"\n}\n\ntype OrderItem struct {\n ID uint gorm:\"primaryKey\" json:\"-\"\n OrderID string gorm:\"index;size:36\" json:\"-\"\n SKU string gorm:\"index;size:64\" json:\"sku\"\n Name string gorm:\"size:128\" json:\"name\"\n UnitPriceCents int64 json:\"unit_price_cents\"\n Qty int json:\"qty\"\n SubtotalCents int64 json:\"subtotal_cents\"\n}\n\n// Idempotency record\ntype OrderRequest struct {\n ID uint gorm:\"primaryKey\"\n Key string gorm:\"uniqueIndex;size:128\"\n PayloadHash string gorm:\"size:128\"\n OrderID *string\n Status string gorm:\"size:16\" // pending/succeeded/failed\n CreatedAt time.Time\n}\n\n// Request DTO (price由服务端计算,客户端不传价格)\ntype CreateOrderRequest struct {\n StoreID string json:\"store_id\" binding:\"required\"\n Items []CreateOrderItem json:\"items\" binding:\"required,min=1,dive\"\n}\n\ntype CreateOrderItem struct {\n SKU string json:\"sku\" binding:\"required\"\n Qty int json:\"qty\" binding:\"required,min=1\"\n}\n\n// Product for price lookup\ntype Product struct {\n SKU string gorm:\"primaryKey;size:64\"\n Name string\n PriceCents int64\n Active bool\n}\n\n// Dependencies injected\ntype Handler struct {\n DB *gorm.DB\n // MsgBus, Cache, etc.\n}\n\nfunc NewHandler(db *gorm.DB) *Handler { return &Handler{DB: db} }\n\n// Utility\nfunc sha256Hex(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) }\n\n// Middleware should set userID from JWT to context key "userID"\n\n// CreateOrder implements robust, idempotent order creation.\nfunc (h *Handler) CreateOrder(c *gin.Context) {\n // Idempotency-Key required\n idemKey := c.GetHeader("Idempotency-Key")\n if idemKey == "" {\n c.JSON(http.StatusBadRequest, gin.H{"error": "Idempotency-Key header required"})\n return\n }\n\n var req CreateOrderRequest\n if err := c.ShouldBindJSON(&req); err != nil {\n c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request", "detail": err.Error()})\n return\n }\n userID := c.GetString("userID")\n if userID == "" {\n c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})\n return\n }\n\n payloadBytes, _ := json.Marshal(req)\n payloadHash := sha256Hex(payloadBytes)\n\n var existing OrderRequest\n tx := h.DB.WithContext(c.Request.Context())\n if err := tx.Where("key = ?", idemKey).First(&existing).Error; err == nil {\n // If request exists, return consistent result\n if existing.PayloadHash != payloadHash {\n c.JSON(http.StatusConflict, gin.H{"error": "idempotency key conflict"})\n return\n }\n if existing.OrderID != nil {\n var ord Order\n if err := tx.Preload("Items").First(&ord, "id = ?", *existing.OrderID).Error; err == nil {\n c.JSON(http.StatusOK, ord)\n return\n }\n }\n // pending: fallthrough to attempt completion\n } else if !errors.Is(err, gorm.ErrRecordNotFound) {\n c.JSON(http.StatusInternalServerError, gin.H{"error": "db error"})\n return\n }\n\n // transactional creation\n var created Order\n err := tx.Transaction(func(t *gorm.DB) error {\n // create placeholder idempotency record (unique key enforces single winner)\n reqRec := OrderRequest{Key: idemKey, PayloadHash: payloadHash, Status: "pending"}\n if err := t.Create(&reqRec).Error; err != nil {\n // another concurrent request won; re-read and return\n if errors.Is(err, gorm.ErrDuplicatedKey) {\n if err := t.Where("key = ?", idemKey).First(&existing).Error; err == nil && existing.OrderID != nil {\n return nil // will read after tx\n }\n }\n return err\n }\n\n // price lookup\n skus := make([]string, 0, len(req.Items))\n for _, it := range req.Items { skus = append(skus, it.SKU) }\n var products []Product\n if err := t.Where("sku IN ? AND active = ?", skus, true).Find(&products).Error; err != nil { return err }\n priceMap := map[string]Product{}\n for _, p := range products { priceMap[p.SKU] = p }\n // validate all items exist\n var items []OrderItem\n var total int64\n for _, it := range req.Items {\n p, ok := priceMap[it.SKU]\n if !ok { return errors.New("product not found: " + it.SKU) }\n subtotal := p.PriceCents * int64(it.Qty)\n items = append(items, OrderItem{\n SKU: p.SKU,\n Name: p.Name,\n UnitPriceCents: p.PriceCents,\n Qty: it.Qty,\n SubtotalCents: subtotal,\n })\n total += subtotal\n }\n\n ord := Order{\n ID: uuid.NewString(),\n StoreID: req.StoreID,\n UserID: userID,\n Status: "created",\n TotalCents: total,\n Items: items,\n }\n if err := t.Create(&ord).Error; err != nil { return err }\n\n // link idempotency record\n oid := ord.ID\n if err := t.Model(&OrderRequest{}).Where("id = ?", reqRec.ID).\n Updates(map[string]interface{}{"order_id": oid, "status": "succeeded"}).Error; err != nil { return err }\n\n created = ord\n return nil\n })\n\n if err != nil {\n if errors.Is(err, gorm.ErrRecordNotFound) {\n c.JSON(http.StatusBadRequest, gin.H{"error": "invalid items"})\n return\n }\n c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create order", "detail": err.Error()})\n return\n }\n\n // reload items (if we returned early on duplicate)\n if created.ID == "" && existing.OrderID != nil {\n var ord Order\n if err := tx.Preload("Items").First(&ord, "id = ?", *existing.OrderID).Error; err == nil {\n c.JSON(http.StatusOK, ord)\n return\n }\n c.JSON(http.StatusInternalServerError, gin.H{"error": "idempotent order retrieval failed"})\n return\n }\n\n c.JSON(http.StatusCreated, created)\n}\n\n// Router setup example\n// func SetupRoutes(r *gin.Engine, h Handler) {\n// r.Use(otelgin.Middleware("order-service")) // tracing\n// api := r.Group("/api").Use(JWTMiddleware())\n// api.POST("/orders", h.CreateOrder)\n// }\n",
"project_structure": [
"移动零售套件/",
"├─ mobile/",
"│ ├─ app/",
"│ │ ├─ lib/",
"│ │ │ ├─ main.dart",
"│ │ │ ├─ core/",
"│ │ │ │ ├─ config/app_config.dart",
"│ │ │ │ ├─ theme/theme_provider.dart",
"│ │ │ │ ├─ network/http_client.dart",
"│ │ │ │ ├─ storage/hive_box.dart",
"│ │ │ │ ├─ sync/offline_queue.dart",
"│ │ │ │ ├─ sync/conflict_resolver.dart",
"│ │ │ │ ├─ auth/jwt_manager.dart",
"│ │ │ ├─ features/",
"│ │ │ │ ├─ auth/login_page.dart",
"│ │ │ │ ├─ store/store_switcher.dart",
"│ │ │ │ ├─ catalog/product_list_page.dart",
"│ │ │ │ ├─ cart/cart_provider.dart",
"│ │ │ │ ├─ order/order_submit_service.dart",
"│ │ │ │ ├─ inventory/inventory_sync_task.dart",
"│ │ │ ├─ routes/app_router.dart",
"│ │ │ ├─ analytics/otel_exporter_stub.dart",
"│ │ ├─ pubspec.yaml",
"│ │ ├─ analysis_options.yaml",
"│ │ ├─ test/",
"│ │ │ ├─ integration/",
"│ │ │ │ ├─ login_flow_test.dart",
"│ │ │ │ ├─ order_submit_test.dart",
"│ │ │ ├─ unit/",
"│ │ │ │ ├─ cart_provider_test.dart",
"│ ├─ android/ (Flutter 默认)",
"│ ├─ ios/ (Flutter 默认)",
"├─ services/",
"│ ├─ order/",
"│ │ ├─ cmd/order-service/main.go",
"│ │ ├─ internal/",
"│ │ │ ├─ http/router.go",
"│ │ │ ├─ http/middleware/jwt.go",
"│ │ │ ├─ domain/order.go",
"│ │ │ ├─ app/handlers.go",
"│ │ │ ├─ repo/order_repo.go",
"│ │ │ ├─ pricing/product_repo.go",
"│ │ │ ├─ idempotency/store.go",
"│ │ │ ├─ events/nats_publisher.go",
"│ │ │ ├─ observability/tracing.go",
"│ │ ├─ pkg/",
"│ │ │ ├─ config/config.go",
"│ │ │ ├─ db/gorm_mysql.go",
"│ │ │ ├─ cache/redis.go",
"│ │ │ ├─ search/meilisearch.go",
"│ │ │ ├─ msg/nats.go",
"│ │ │ ├─ logger/logger.go",
"│ │ ├─ migrations/",
"│ │ │ ├─ 0001_init.sql",
"│ │ │ ├─ 0002_products.sql",
"│ ├─ inventory/",
"│ │ ├─ cmd/inventory-service/main.go",
"│ │ ├─ internal/... (库存预留/盘点接口)",
"│ ├─ payment/",
"│ │ ├─ cmd/payment-service/main.go",
"│ │ ├─ internal/... (支付下单/回调)",
"│ ├─ user/",
"│ │ ├─ cmd/user-service/main.go",
"│ │ ├─ internal/... (登录/JWT发放/门店绑定)",
"├─ gateway/",
"│ ├─ cmd/gateway/main.go",
"│ ├─ internal/",
"│ │ ├─ http/gin_server.go",
"│ │ ├─ bff/aggregators.go",
"│ │ ├─ middleware/auth.go",
"│ │ ├─ observability/tracing.go",
"│ ├─ pkg/",
"│ │ ├─ config/config.go",
"│ │ ├─ rate/limiter.go",
"│ │ ├─ cache/redis.go",
"├─ infra/",
"│ ├─ config/",
"│ │ ├─ .env.example",
"│ │ ├─ app.yaml",
"│ │ ├─ db.yaml",
"│ │ ├─ redis.yaml",
"│ │ ├─ meilisearch.yaml",
"│ │ ├─ nats.yaml",
"│ │ ├─ otel-collector.yaml",
"│ │ ├─ prometheus.yaml",
"│ ├─ deploy/",
"│ │ ├─ docker/",
"│ │ │ ├─ order.Dockerfile",
"│ │ │ ├─ inventory.Dockerfile",
"│ │ │ ├─ payment.Dockerfile",
"│ │ │ ├─ gateway.Dockerfile",
"│ │ │ ├─ mobile.Dockerfile (可选用于Web打包)",
"│ │ │ ├─ docker-compose.dev.yml",
"│ │ ├─ k8s/",
"│ │ │ ├─ namespace.yaml",
"│ │ │ ├─ order-deploy.yaml",
"│ │ │ ├─ inventory-deploy.yaml",
"│ │ │ ├─ payment-deploy.yaml",
"│ │ │ ├─ gateway-deploy.yaml",
"│ │ │ ├─ mysql-statefulset.yaml",
"│ │ │ ├─ redis-deploy.yaml",
"│ │ │ ├─ meilisearch-deploy.yaml",
"│ │ │ ├─ nats-deploy.yaml",
"│ │ │ ├─ otel-collector-deploy.yaml",
"│ │ │ ├─ prometheus-deploy.yaml",
"│ │ ├─ helm/ (可选)",
"│ ├─ db/",
"│ │ ├─ seed/",
"│ │ │ ├─ products.json",
"│ │ ├─ migrations/ (复用 services//migrations)",
"│ ├─ scripts/",
"│ │ ├─ migrate.sh",
"│ │ ├─ seed.sh",
"│ │ ├─ dev_up.sh",
"│ │ ├─ fmt_lint.sh",
"├─ scripts/",
"│ ├─ scaffold.sh (生成模块/handler/测试样板)",
"│ ├─ makefile",
"│ ├─ ci/",
"│ │ ├─ github/",
"│ │ │ ├─ workflows/ci.yml",
"│ │ ├─ gitlab-ci.yml (可选)",
"├─ pkg/ (后端共享库)",
"│ ├─ auth/",
"│ │ ├─ jwt.go",
"│ ├─ observability/",
"│ │ ├─ otel.go",
"│ │ ├─ metrics.go",
"│ ├─ http/",
"│ │ ├─ response.go",
"│ ├─ idempotency/",
"│ │ ├─ middleware.go",
"├─ .golangci.yml",
"├─ go.work (多模块管理)",
"├─ README.md"
]
}
帮助开发者在面对复杂需求时,高效生成多技术栈适配的项目框架,涵盖需求解析、代码初始化、优化等功能,一站式提升开发速度和代码质量。
需要快速启动多种技术栈项目的工程师,使用提示词加速框架搭建并定制开发结构。
希望借助自动化工具快速生成基本框架,避免技术瓶颈,提高学习与动手时间效率。
需为团队设定项目基础标准和框架思路,用以统一代码结构并推进团队开发效率。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期