Token导航 LogoToken导航TokenDH.com
研究检索external-servicegithub未标认证来源可访问许可证需确认审计通过

implement-repository-pattern实施存储库模式

Agent Skill

用于围绕 GitHub 仓库、Issue、Pull Request、分支、提交和代码协作流程提供辅助能力。它适合让 Agent 查询项目状态、整理变更、辅助创建或检查协作事项,并把仓库中的信息转成可执行的下一步。使用时需要区分只读查询和写入操作;涉及创建 PR、修改 Issue、推送分支或访问私有仓库时,应确认 token 权限、目标仓库范围和用户授权。

总安装

196

周安装

8

GitHub Stars

1

下载量

63
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/dawiddutoit/custom-claude --skill implement-repository-pattern

简介

用于围绕 GitHub 仓库、Issue、Pull Request、分支、提交和代码协作流程提供辅助能力,适合查询项目状态或整理变更。

  • 适用于创建或检查协作事项,并将仓库信息转为可执行的下一步。
  • 使用时需区分只读查询和写入操作,涉及 PR 或 Issue 修改时需确认 token 权限。
  • 访问私有仓库或推送分支时应确保用户授权和目标仓库范围正确。
  • implement-repository-pattern 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Works with Python files in domain/repositories/ and infrastructure/ directories.

Implement Repository Pattern

Table of Contents

Core Sections

- Core responsibility: Create repositories with Protocol/Implementation separation

- Fastest path: Create repository from user request to working implementation

- Step 1: Create Domain Protocol (Interface) - Step 2: Create Infrastructure Implementation - Step 3: Add Cypher Queries - Step 4: Register in Container - Step 5: Create Tests

- Example 1: Simple CRUD Repository - Example 2: Repository with Complex Domain Model - Example 3: Repository with Pagination

Patterns & Best Practices

- Pattern 1: Query Parameter Validation - Pattern 2: ServiceResult Propagation - Pattern 3: Resource Lifecycle

- Critical issues to watch for in repository implementation

- Complete validation before marking repository done

Supporting Resources

- Dependencies, project structure, and setup requirements

- templates/protocol-template.py - Repository protocol skeleton - templates/implementation-template.py - Neo4j implementation skeleton - templates/test-template.py - Test suite skeleton - references/pattern-guide.md - Complete pattern catalog - references/troubleshooting.md - Common issues and solutions - scripts/analyze_queries.py - Analyze Cypher queries in repository implementations - scripts/generate_repository.py - Generate repository pattern files with domain protocol and implementation - scripts/validate_repository_patterns.py - Validate repository pattern compliance across the codebase

Purpose

Create repositories following Clean Architecture principles with Protocol (domain layer) and Implementation (infrastructure layer) separation. Ensures proper dependency inversion, ServiceResult return types, and resource lifecycle management.

When to Use

Use this skill when:

  • Adding new data access layer - Creating persistence for domain models
  • Creating database interaction - Implementing queries and commands against data stores
  • Implementing persistence - Storing and retrieving domain entities
  • Need to store/retrieve domain models - Data access abstraction required

Trigger phrases:

  • "Create a repository for X"
  • "Implement data access for Y"
  • "Add persistence layer for Z"
  • "Store/retrieve domain model X"

Quick Start

User: "Create a repository for storing search history"

What happens:

  1. Create Protocol interface in domain/repositories/search_history_repository.py
  2. Create Neo4j implementation in infrastructure/neo4j/search_history_repository.py
  3. Implement ManagedResource for lifecycle
  4. Use ServiceResult for all operations
  5. Add required Cypher queries

Result: ✅ Repository with Protocol + Implementation ready for dependency injection

Instructions

Step 1: Create Domain Protocol (Interface)

Location: src/project_watch_mcp/domain/repositories/{name}_repository.py

Pattern:

from abc import ABC, abstractmethod
from project_watch_mcp.domain.common import ServiceResult

class {Name}Repository(ABC):
    """Port for {purpose} storage and retrieval.

    This interface defines the contract for {operations}.
    Concrete implementations will be provided in the infrastructure layer.
    """

    @abstractmethod
    async def {operation}(self, param: Type) -> ServiceResult[ReturnType]:
        """Brief description of operation.

        Args:
            param: Description

        Returns:
            ServiceResult[ReturnType]: Success with data or Failure on errors
        """
        pass

Key Requirements:

  • Inherit from ABC
  • Use @abstractmethod decorator
  • Return ServiceResult[T] for all operations
  • Document expected behavior in docstrings
  • No implementation details (pure interface)

Step 2: Create Infrastructure Implementation

Location: src/project_watch_mcp/infrastructure/neo4j/{name}_repository.py

Pattern:

from neo4j import AsyncDriver, RoutingControl
from project_watch_mcp.config.settings import Settings
from project_watch_mcp.domain.common import ServiceResult
from project_watch_mcp.domain.repositories.{name}_repository import {Name}Repository
from project_watch_mcp.domain.services.resource_manager import ManagedResource

class Neo4j{Name}Repository({Name}Repository, ManagedResource):
    """Neo4j adapter implementing {Name}Repository interface."""

    def __init__(self, driver: AsyncDriver, settings: Settings):
        if not driver:
            raise ValueError("Neo4j driver is required")
        if not settings:
            raise ValueError("Settings is required")

        self.driver = driver
        self.settings = settings
        self.database = settings.neo4j.database_name

    async def _execute_with_retry(
        self,
        query: str,
        parameters: dict[str, Any] | None = None,
        routing: RoutingControl = RoutingControl.WRITE,
    ) -> ServiceResult[list[dict]]:
        """Execute query with parameter validation and retry logic."""
        # Validate before executing
        validation_result = validate_and_build_query(query, parameters, strict=True)
        if validation_result.is_failure:
            return ServiceResult.fail(f"Validation failed: {validation_result.error}")

        validated_query = validation_result.data

        try:
            records, _, _ = await self.driver.execute_query(
                cast(LiteralString, validated_query.query),
                validated_query.parameters,
                database_=self.database,
                routing_=routing,
            )
            return ServiceResult.ok([dict(record) for record in records])
        except Neo4jError as e:
            return ServiceResult.fail(f"Database error: {str(e)}")

    async def close(self) -> None:
        """Close and cleanup resources (ManagedResource protocol)."""
        # Repository-specific cleanup if needed
        pass

Key Requirements:

  • Implement Protocol interface
  • Inherit from ManagedResource
  • Required constructor params: driver: AsyncDriver, settings: Settings
  • Validate parameters in constructor (if not driver: raise ValueError)
  • Use _execute_with_retry() for all database operations
  • Implement close() for resource cleanup
  • All operations return ServiceResult[T]

Step 3: Add Cypher Queries

Location: src/project_watch_mcp/infrastructure/neo4j/queries.py

Pattern:

class CypherQueries:
    # Existing queries...

    # {Name}Repository Queries
    GET_{ENTITY} = """
    MATCH (e:{Label} {project_name: $project_name, id: $id})
    RETURN e
    """

    SAVE_{ENTITY} = """
    MERGE (e:{Label} {project_name: $project_name, id: $id})
    SET e += $properties
    SET e.updated_at = datetime()
    RETURN e
    """

Key Requirements:

  • Group queries by repository
  • Use parameterized queries (prevent injection)
  • Use MERGE for upsert operations
  • Include timestamp management
  • Document query purpose

See: references/query-patterns.md for common patterns

Step 4: Register in Container

Location: src/project_watch_mcp/infrastructure/container.py

Pattern:

async def {name}_repository(self) -> {Name}Repository:
    """Provide {Name}Repository implementation."""
    driver = await self.neo4j_driver()
    settings = await self.settings()
    return Neo4j{Name}Repository(driver, settings)

Key Requirements:

  • Return type is Protocol (not implementation)
  • Inject dependencies (driver, settings)
  • Use async/await for resource initialization
  • Follow naming convention: {name}_repository()

Step 5: Create Tests

Unit Tests: tests/unit/infrastructure/neo4j/test_{name}_repository.py Integration Tests: tests/integration/infrastructure/neo4j/test_{name}_repository.py

Pattern:

@pytest.mark.asyncio
async def test_save_{entity}_success(mock_driver, settings):
    """Test successful {entity} save operation."""
    # Arrange
    repo = Neo4j{Name}Repository(mock_driver, settings)
    mock_driver.execute_query.return_value = (
        [{"e": {"id": "test", "name": "Test"}}],
        None,
        None,
    )

    # Act
    result = await repo.save_{entity}(entity_data)

    # Assert
    assert result.is_success
    assert result.data is not None

Key Requirements:

  • Test both success and failure cases
  • Mock driver.execute_query for unit tests
  • Test parameter validation
  • Test ServiceResult.ok() and ServiceResult.fail() paths
  • Integration tests use real Neo4j instance

Examples

Example 1: Simple CRUD Repository

Protocol:

class SearchHistoryRepository(ABC):
    @abstractmethod
    async def save_query(self, query: str, user_id: str) -> ServiceResult[None]:
        pass

    @abstractmethod
    async def get_recent_queries(self, user_id: str, limit: int) -> ServiceResult[list[str]]:
        pass

Implementation:

class Neo4jSearchHistoryRepository(SearchHistoryRepository, ManagedResource):
    async def save_query(self, query: str, user_id: str) -> ServiceResult[None]:
        cypher = """
        CREATE (q:SearchQuery {query: $query, user_id: $user_id, timestamp: datetime()})
        """
        result = await self._execute_with_retry(cypher, {"query": query, "user_id": user_id})
        return ServiceResult.ok(None) if result.is_success else result

Example 2: Repository with Complex Domain Model

For advanced patterns, see references/pattern-guide.md:

  • Converting Neo4j records to domain models
  • Handling nested relationships
  • Batch operations
  • Transaction management

Example 3: Repository with Pagination

For pagination patterns, see references/pattern-guide.md:

  • Cursor-based pagination
  • Offset-based pagination
  • Performance considerations

Requirements

Dependencies:

  • neo4j>=5.0.0 - Async driver
  • project_watch_mcp.domain.common - ServiceResult
  • project_watch_mcp.domain.services.resource_manager - ManagedResource
  • project_watch_mcp.config.settings - Settings injection

Project Structure:

src/project_watch_mcp/
├── domain/
│   └── repositories/
│       └── {name}_repository.py     # Protocol (ABC)
├── infrastructure/
│   └── neo4j/
│       ├── {name}_repository.py     # Implementation
│       └── queries.py               # Cypher queries
└── tests/
    ├── unit/infrastructure/neo4j/
    │   └── test_{name}_repository.py
    └── integration/infrastructure/neo4j/
        └── test_{name}_repository.py

Common Patterns

Pattern 1: Query Parameter Validation

Always validate query parameters before execution:

validation_result = validate_and_build_query(query, parameters, strict=True)
if validation_result.is_failure:
    return ServiceResult.fail(f"Validation failed: {validation_result.error}")

Pattern 2: ServiceResult Propagation

Chain ServiceResult operations:

result = await self._execute_with_retry(query, params)
if result.is_failure:
    return ServiceResult.fail(f"Failed to save: {result.error}")

# Transform data and return success
return ServiceResult.ok(transformed_data)

Pattern 3: Resource Lifecycle

Implement ManagedResource for proper cleanup:

async def close(self) -> None:
    """Cleanup repository-specific resources."""
    # Driver is managed externally by container
    # Only cleanup repository-specific resources here
    logger.debug(f"{self.__class__.__name__} cleanup complete")

See: references/pattern-guide.md for complete pattern catalog

Red Flags - STOP

If you see any of these, investigate immediately:

  1. ❌ Protocol in infrastructure layer → Must be in domain
  2. ❌ Return None on error → Use ServiceResult.fail()
  3. ❌ Optional settings parameter → Must be required
  4. ❌ Direct driver usage → Use _execute_with_retry()
  5. ❌ Missing parameter validation → Validate in constructor
  6. ❌ Raw Cypher in methods → Use CypherQueries class
  7. ❌ Synchronous methods → All methods must be async
  8. ❌ Missing ManagedResource → Required for lifecycle
  9. ❌ Return domain models from Neo4j layer → Convert in repository
  10. ❌ Missing tests → Must have unit + integration tests

Success Checklist

Before marking repository complete:

  • Protocol exists in domain/repositories/
  • Implementation exists in infrastructure/neo4j/
  • Constructor validates driver and settings
  • All methods return ServiceResult[T]
  • Implements ManagedResource with close()
  • Uses _execute_with_retry() for all operations
  • Queries defined in CypherQueries
  • Registered in container
  • Unit tests passing (mocked driver)
  • Integration tests passing (real Neo4j)
  • Quality gates pass (./scripts/check_all.sh)
  • Documentation updated (if new pattern)

See Also

Related Skills:

  • implement-dependency-injection - For container registration
  • validate-layer-boundaries - For architecture compliance
  • run-quality-gates - For validation before commit

Last Updated: 2025-10-18

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.42%
按下载量换算24

Claude

30.71%
按下载量换算19

Cursor

18.14%
按下载量换算11

Gemini CLI

9.7%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

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

来源信息

继续浏览同类 Skills