Token导航 LogoToken导航

Agent Skill · 研究检索

service-pattern-nestjs(服务模式 nestjs)

service-pattern-nestjs 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

service-pattern-nestjs 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 71,838。

总安装 192周安装 8GitHub Stars 1下载 64核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:service-pattern-nestjs(服务模式 nestjs)
来源仓库:https://github.com/allenlin90/eridu-services
仓库路径:skills/service-pattern-nestjs
安装命令:
npx skills add https://github.com/allenlin90/eridu-services --skill service-pattern-nestjs
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/allenlin90/eridu-services --skill service-pattern-nestjs

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

service-pattern-nestjs 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。适用于 NestJS 框架下的服务模块化、依赖注入与 CQRS 实现指导。

提供装饰器使用最佳实践与单元测试编写模板。输出内容以 TypeScript 为主,请确保开发环境支持相应类型检查。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

来源仓库内路径:skills/service-pattern-nestjs

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/allenlin90/eridu-services --skill service-patt…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

service-pattern-nestjs 怎么安装?

在终端执行 npx skills add https://github.com/allenlin90/eridu-services --skill service-pattern-nestjs。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

service-pattern-nestjs 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

service-pattern-nestjs 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

service-pattern-nestjs 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

service-pattern-nestjs 用的人多吗?

公开数据是累计安装 192 次,近一周安装 8 次,下载 64 次,GitHub 1 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

service-pattern-nestjs 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
service-pattern-nestjs

服务模式 nestjs · 本页

1921需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Service Pattern - NestJS

Complete implementation guide for NestJS Services in Eridu.

Canonical Examples

Study these real implementations as the source of truth:

Detailed code examples: See references/service-examples.md


Core Responsibilities

Services act as the business logic layer. They should:

  1. Implement business logic - Handle domain rules and operations
  2. Coordinate data access - Call repositories to fetch/persist data
  3. Validate input - Check data before persistence
  4. Handle errors - Transform low-level errors to domain errors
  5. Coordinate operations - Orchestrate multi-entity workflows
  6. Manage transactions - Ensure data consistency

Domain Transition Rule

If an operation is a business-state transition (not a generic field update), model it as an explicit service action with clear invariants.

Examples of required invariants:

  1. allowed current state(s),
  2. blocking conditions (for example active tasks),
  3. required audit context (reason, actor, timestamp),
  4. idempotent behavior under retries/concurrency.

Controller PATCH handlers should call this explicit service action rather than bypassing invariants through generic update payloads.


Service Architecture

Layered Pattern:

Controller (HTTP boundary)
    ↓
Service (Business logic)
    ├─ Model Services (single entity)
    └─ Orchestration Services (multiple entities)
    ↓
Repository (Data access)
    ↓
Database

Model Services

Handle CRUD operations for a single entity. Focused on single entity, simple CRUD operations, dependency on one or more repositories.

Orchestration Services

Coordinate multiple entities for complex workflows. Handle complex business workflows, use transactions for atomicity.


Model Service Structure

🔴 Critical: Extend BaseModelService<T> for standard CRUD.

import { Injectable } from '@nestjs/common';
import { BaseModelService } from '@/lib/services/base-model.service';
import { UtilityService } from '@/utility/utility.service';

@Injectable()
export class UserService extends BaseModelService {
  // UID_PREFIX has NO trailing underscore (e.g., 'user', not 'user_')
  static readonly UID_PREFIX = 'user';
  protected readonly uidPrefix = UserService.UID_PREFIX;

  constructor(
    private readonly userRepository: UserRepository,
    protected readonly utilityService: UtilityService,
  ) {
    super(utilityService);
  }
}

When Does a Model Service Justify Existing?

A model service exists to:

  1. Generate UIDs (this.generateUid()) — even thin services serve this purpose
  2. Enforce invariants before/after persistence
  3. Translate domain payloads into repository calls
  4. Be the stable public API of the module

A service with only pass-through methods is acceptable when:

  • It provides a consistent pattern with sibling modules
  • It generates UIDs (join table services)
  • Its methods may gain logic in the future

A service that does NOT generate UIDs and has zero logic should be questioned — consider whether the orchestration should just call the parent module's service.


Avoiding ORM Coupling in Services

🔴 Critical: Services MUST NEVER import or use Prisma types in method signatures or business logic.

Why: We use the repository pattern to encapsulate all database concerns. Services should be completely decoupled from the ORM to allow changing the database layer without touching business logic.

Rule 1: Define Payload Types in Schema Files

Schema files MAY use Prisma.* types to define payload types:

// ✅ ALLOWED: In schema file
import type { Prisma } from '@prisma/client';

export type CreateTaskTemplatePayload = Omit<
  Prisma.TaskTemplateCreateInput,
  'uid' | 'version'
> & {
  uid?: string;
  currentSchema: any;
};

Rule 2: Services Import Payload Types, NOT Prisma Types

// ✅ GOOD: Service imports payload type from schema
import type { CreateTaskTemplatePayload } from './schemas/task-template.schema';

async createTemplateWithSnapshot(
  payload: CreateTaskTemplatePayload,
): Promise<TaskTemplate> {
  return this.repository.create({
    ...payload,
    uid: this.generateUid(),
  });
}
// ❌ BAD: Service imports Prisma types
import { Prisma } from '@prisma/client';

async create(payload: Prisma.TaskTemplateCreateInput): Promise<TaskTemplate> {
  // ...
}

Rule 3: Use Parameters<Repo['method']> for Pass-Through

For methods that simply pass arguments to the repository, use Parameters<> to match the repository signature:

// ✅ GOOD: Service signature matches repository
async getTaskTemplates(
  ...args: Parameters<TaskTemplateRepository['findPaginated']>
): Promise<{ data: TaskTemplate[]; total: number }> {
  return this.repository.findPaginated(...args);
}

async findOne(
  ...args: Parameters<TaskTemplateRepository['findOne']>
): Promise<TaskTemplate | null> {
  return this.repository.findOne(...args);
}

Benefits:

  • Service has zero Prisma imports
  • Service signature automatically matches repository
  • Changing ORM only requires updating repository
  • Service tests don't need to mock Prisma types

Tradeoff awareness: Parameters<Repository['method']> couples the service method signature to the repository signature. Changing the repository method signature changes the service's public API.

Use this pattern when:

  • The method is a genuine pass-through with no business logic
  • The service needs to expose a repository query for orchestration callers

Mark these as @internal if they are not intended for controllers:

/** @internal For orchestration use only. Controllers use findByUid(). */
async findOne(...args: Parameters<TaskRepository['findOne']>)

Rule 5: Never Call Zod .parse() Inside a Service

🔴 Critical: Services MUST NOT call Zod .parse() on their input payloads.

Why: The controller/DTO layer (via nestjs-zod and ZodValidationPipe) is the HTTP boundary. By the time a method reaches the service, the payload has already been validated and is fully typed. Parsing again is a double-parse, it moves validation responsibility into the wrong layer, and it breaks the single-responsibility principle.

// ❌ BAD: Service re-validates a payload that was already validated by the DTO
import { createUserSchema } from '@eridu/api-types/users';

async run(payload: unknown): Promise<Result> {
  const validated = createUserSchema.parse(payload); // ← WRONG
  ...
}

// ✅ GOOD: Service accepts the already-typed payload
import type { CreateUserRequest } from '@eridu/api-types/users';

async run(payload: CreateUserRequest): Promise<Result> {
  // payload is already validated — use it directly
  ...
}

The matching controller uses a Zod DTO to handle validation before the service is called:

// Controller DTO (nestjs-zod validates on ingress):
export class CreateUserDto extends createZodDto(createUserRequestSchema) {}

// Controller method — payload is validated before service.run() is called:
@Post()
async create(@Body() payload: CreateUserDto) {
  return this.userService.run(payload); // typed, already valid
}

Anti-pattern signature:

// Any service method with `payload: unknown` that calls `.parse()` is wrong.
async doSomething(payload: unknown): Promise<X> {
  const data = someSchema.parse(payload); // ← move this to a DTO

This rule also applies to DTO composition. When building a derived DTO schema (e.g., a detail DTO that extends a base DTO), do NOT call .parse() of the base DTO inside the derived transform. Instead, inline the transform logic so the object is only parsed once through a single .pipe() chain.

// ❌ BAD: nested .parse() inside transform causes double validation
export const detailDto = baseSchema.extend({ extra: z.string() })
  .transform((obj) => ({
    ...baseDto.parse(obj),   // ← re-runs full base validation
    extra: obj.extra,
  }))
  .pipe(detailApiSchema);

// ✅ GOOD: inline the transform, single parse pass
export const detailDto = baseSchema.extend({ extra: z.string() })
  .transform((obj) => ({
    id: obj.uid,
    name: obj.name,
    // ... inline base fields directly
    extra: obj.extra,
  }))
  .pipe(detailApiSchema);

Rule 4: Repository Owns Where-Clause Building

The repository layer is responsible for building ORM-specific where clauses. Services pass domain-level parameters:

// ✅ GOOD: Repository accepts domain parameters
// Repository method signature:
async findPaginated(params: {
  skip?: number;
  take?: number;
  name?: string;
  uid?: string;
  includeDeleted?: boolean;
  studioUid?: string;
  orderBy?: 'asc' | 'desc';
}): Promise<{ data: TaskTemplate[]; total: number }>

The repository then builds the Prisma where clause internally:

// Inside repository:
const where: Prisma.TaskTemplateWhereInput = {};

if (!includeDeleted) {
  where.deletedAt = null;
}

if (name) {
  where.name = { contains: name, mode: 'insensitive' };
}

if (studioUid) {
  where.studio = { uid: studioUid };
}

CRUD Operations

Create with ID Generation

async createUser(data: CreateUserDto): Promise<User> {
  return this.userRepository.create({
    uid: this.generateUid(), // Helper from BaseModelService
    email: data.email,
    name: data.name,
  });
}

Read with Verification

async getUserById(uid: string): Promise<User> {
  const user = await this.userRepository.findByUid(uid);
  if (!user) throw HttpError.notFound('User', uid);
  return user;
}

Error Handling by Service Type

Differentiate your error handling strategy based on the service type:

1. Model Services (Single Entity)

Pattern: Return null, let Controller handle 404.

// Service
async getUserById(uid: string): Promise<User | null> {
  return this.userRepository.findByUid(uid);
}

// Controller
@Get(':id')
async getUser(@Param('id') id: string) {
  const user = await this.userService.getUserById(id);
  this.ensureResourceExists(user, 'User', id); // Throws 404
  return user;
}
2. Orchestration Services (Complex Workflows)

Pattern: Throw Domain Exceptions or business logic errors directly.

Orchestration services often enforce rules that the controller cannot know about (e.g., "User must be a member of this Studio to be assigned").

// Service
async assignUserToStudio(userUid: string, studioUid: string) {
  const isMember = await this.membershipService.isMember(userUid, studioUid);

  if (!isMember) {
    // ✅ ACCEPTABLE: detailed business error
    throw HttpError.forbidden('User is not a member of this studio');
  }
}
[!TIP] Preferred: Throw custom Domain Exceptions (e.g., InvalidAssigneeError) and use a global Exception Filter to map them to HTTP responses. Acceptable: Use HttpError utility for immediate feedback in non-critical paths. Avoid: Throwing generic NotFoundException for simple lookups — stick to null + ensureResourceExists.
3. Update/Delete Operations

Controller verifies existence BEFORE calling the mutation service (Controller-Checks Pattern).

// Controller
@Patch(':id')
async updateUser(@Param('id') id: string, @Body() dto: UpdateUserDto) {
  // 1. Verify existence
  const user = await this.userService.getUserById(id);
  this.ensureResourceExists(user, 'User', id);

  // 2. Perform operation
  return this.userService.updateUser(id, dto);
}

@Delete(':id')
async deleteUser(@Param('id') id: string) {
  // 1. Verify existence
  const user = await this.userService.getUserById(id);
  this.ensureResourceExists(user, 'User', id);

  // 2. Perform operation
  await this.userService.deleteUser(id);
}

Bulk Operations

🟡 Recommended: Use Repository bulk methods, DO NOT loop in Service.

async createManyUsers(users: CreateUserDto[]) {
  // Map DTOs to internal structure (e.g. add UIDs)
  const data = users.map(u => ({
    ...u,
    uid: this.generateUid()
  }));

  // Single DB Call
  return this.userRepository.createMany(data);
}

Optimistic Locking Pattern

🟡 Recommended: For versioned entities, use version checks to prevent concurrent update conflicts.

async updateTemplateWithSnapshot(
  where: Parameters<TaskTemplateRepository['updateWithVersionCheck']>[0],
  payload: Parameters<TaskTemplateRepository['updateWithVersionCheck']>[1],
): Promise<TaskTemplate> {
  if (payload.currentSchema && !this.validateSchema(payload.currentSchema)) {
    throw HttpError.badRequest('Invalid schema');
  }

  try {
    if (payload.currentSchema) {
      const newVersion = (payload.version as number) + 1;
      return await this.repository.updateWithVersionCheck(where, {
        name: payload.name,
        description: payload.description,
        currentSchema: payload.currentSchema,
        version: newVersion,
        snapshots: {
          create: {
            version: newVersion,
            schema: payload.currentSchema,
          },
        },
      });
    }

    return await this.repository.update(where, {
      name: payload.name,
      description: payload.description,
    });
  } catch (error) {
    if (error instanceof VersionConflictError) {
      throw HttpError.conflict(
        `Record is out of date. Please refresh your record and try again.`,
      );
    }
    throw error;
  }
}

Including Relations

Question: Should services expose include parameters?

Short Answer: Avoid it when possible, but it's acceptable for internal orchestration APIs.

Recommended Pattern: Dedicated Methods

// ✅ GOOD: Dedicated methods for different data shapes
async getTaskById(uid: string): Promise<Task>
async getTaskWithAssignee(uid: string): Promise<Task & { assignee: User }>
async getTaskWithTemplate(uid: string): Promise<Task & { template: TaskTemplate }>

Acceptable Pattern: Internal Orchestration API

// ✅ ACCEPTABLE: For orchestration services that need flexibility
/**
 * @internal
 * Internal method for orchestration services.
 * Controllers should use dedicated methods like getTaskWithAssignee().
 */
async findOne(
  ...args: Parameters<TaskRepository['findOne']>
): Promise<Task | null> {
  return this.taskRepository.findOne(...args);
}

When to use each:

  • Dedicated methods: For controller-facing APIs (preferred)
  • Parameters spread: For internal flexibility (acceptable, mark as @internal)

Orchestration Services

🔴 Critical: Coordinate multiple services/repositories using Transactions.

See Database Patterns for transaction rules.

import { Transactional } from '@nestjs-cls/transactional';

@Injectable()
export class ShowOrchestrationService {
  constructor(
    private readonly showService: ShowService,
    private readonly assignmentService: AssignmentService,
  ) {}

  // Apply @Transactional() on the orchestration method — never pass `tx` as a parameter.
  // CLS propagates the transaction automatically to all repository calls.
  @Transactional()
  async createShowWithAssignments(data: CreateShowDto) {
    const show = await this.showService.createShow(data);
    await this.assignmentService.createAssignments(show.id, data.assignments);
    return show;
  }
}
[!WARNING] Never use the old $transaction(async (tx) => {...}) pattern with tx parameter passing. This is the legacy pattern. All new orchestration must use @Transactional(). Repositories access the active CLS transaction client via TransactionHost injected by the adapter.

Best Practices Checklist

  • Extend BaseModelService
  • Define UID_PREFIX static constant (no trailing underscore)
  • Inject UtilityService
  • Use this.generateUid()
  • 🔴 Critical: Define Payload types in schema files (not in service)
  • 🔴 Critical: NEVER call Zod .parse() inside a service — accept typed payloads, let the DTO layer validate
  • 🔴 Critical: NEVER import or use Prisma.* types in service method signatures
  • 🔴 Critical: Use Parameters<Repository['methodName']> for pass-through methods
  • 🔴 Critical: Delegate filter building to repository layer (not service)
  • 🔴 Critical: Return null (don't throw) if record missing in Read operations
  • 🔴 Critical: Let Controller handle 404 checks (using ensureResourceExists)
  • 🔴 Critical: Never throw NotFoundException in Service (business logic only)
  • Catch VersionConflictError and rethrow as HttpError.conflict()
  • 🟡 Recommended: Prefer dedicated methods over exposing include parameters
  • Mark methods with @internal JSDoc if they're for orchestration only

Related Skills

平台分布

Codex

38.24%
按下载量换算24

Claude

31.1%
按下载量换算20

Cursor

16.36%
按下载量换算10

Gemini CLI

9.52%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills