kotlin-backend-patterns
Use when the user asks about Koin DI, MockK tests, runTest coroutine testing, Kotlin repository and service layers, DTO mapping with extension functions or…
от j4flmao★ 47 звёзд на GitHub
Установить kotlin-backend-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Kotlin Backend Patterns
Purpose
Standardize common Kotlin backend implementation patterns: repository, service, DTO mapping, dependency injection, and testing.
Agent Protocol
Trigger
User request includes: kotlin pattern, repository kotlin, service layer kotlin, koin setup, mockk testing, kotlin di, coroutine pattern, kotlin testing.
Input Context
- Framework (Ktor, Spring WebFlux, http4k)
- DI framework (Koin, Kodein, Spring)
- Test framework (kotlin.test, MockK)
- Serialization approach (kotlinx.serialization, Jackson)
Output Artifact
A markdown document containing:
- Repository pattern with coroutines
- Service layer abstraction
- DTO / domain mapping
- DI module wiring
- Unit test examples with MockK
- Integration test patterns
Response Format
Produce the artifact directly. No preamble, no postamble, no explanations. No filler, no hedging. Compress output.
Completion Criteria
- Repository abstracted behind interface for testability
- Service layer contains business logic
- DI modules scoped correctly
- Tests cover success, error, and edge cases
- Coroutine dispatchers overridable in tests
Max Response Length
4096 tokens
Workflow
Step 1: Repository Pattern
// domain/OrderRepository.kt
interface OrderRepository {
suspend fun findById(id: UUID): Order?
suspend fun findByCustomerId(customerId: String): List<Order>
suspend fun save(order: Order): Order
suspend fun delete(id: UUID)
suspend fun findAll(page: Int, size: Int): PagedResult<Order>
}
data class PagedResult<T>(
val items: List<T>,
val total: Long,
val page: Int,
val size: Int
)
// infrastructure/OrderRepositoryImpl.kt
class OrderRepositoryImpl(private val db: Database) : OrderRepository {
override suspend fun findById(id: UUID): Order? = db.withSession {
OrderTable.select { OrderTable.id eq id }
.map { it.toOrder() }
.singleOrNull()
}
override suspend fun findByCustomerId(customerId: String): List<Order> = db.withSession {
OrderTable.select { OrderTable.customerId eq customerId }
.orderBy(OrderTable.createdAt.desc())
.map { it.toOrder() }
}
override suspend fun save(order: Order): Order = db.withSession {
val entity = order.toEntity()
OrderTable.insert(entity)
order.copy(id = entity.id)
}
override suspend fun delete(id: UUID) = db.withSession {
OrderTable.deleteWhere { OrderTable.id eq id }
}
override suspend fun findAll(page: Int, size: Int): PagedResult<Order> = db.withSession {
val total = OrderTable.selectAll().count()
val items = OrderTable.selectAll()
.orderBy(OrderTable.createdAt.desc())
.limit(size)
.offset((page * size).toLong())
.map { it.toOrder() }
PagedResult(items, total, page, size)
}
}
Step 2: Service Layer
// domain/OrderService.kt
class OrderService(
private val repo: OrderRepository,
private val validator: OrderValidator,
private val eventPublisher: EventPublisher
) {
suspend fun create(request: CreateOrderRequest): Order {
validator.validate(request)
val order = Order.create(
customerId = request.customerId,
items = request.items.map { it.asDomain() },
couponCode = request.couponCode
)
val saved = repo.save(order)
eventPublisher.publish(OrderCreatedEvent(saved.id!!))
return saved
}
suspend fun findById(id: UUID): Order {
return repo.findById(id) ?: throw NotFoundException("Order", id)
}
suspend fun findByCustomerId(customerId: String): List<Order> {
return repo.findByCustomerId(customerId)
}
suspend fun findAll(page: Int, size: Int): PagedResult<Order> {
require(page >= 0) { "Page must be non-negative" }
require(size in 1..100) { "Size must be between 1 and 100" }
return repo.findAll(page, size)
}
suspend fun cancel(id: UUID, reason: String): Order {
val order = repo.findById(id) ?: throw NotFoundException("Order", id)
order.cancel(reason)
val saved = repo.save(order)
eventPublisher.publish(OrderCancelledEvent(saved.id!!, reason))
return saved
}
suspend fun delete(id: UUID) {
val order = repo.findById(id) ?: throw NotFoundException("Order", id)
repo.delete(id)
}
}
// domain/OrderValidator.kt
class OrderValidator {
fun validate(request: CreateOrderRequest) {
require(request.customerId.isNotBlank()) { "customerId must not be blank" }
require(request.items.isNotEmpty()) { "At least one item required" }
request.items.forEachIndexed { index, item ->
require(item.quantity > 0) { "Item $index: quantity must be positive" }
require(item.unitPrice >= 0.0) { "Item $index: unit price must be non-negative" }
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/coroutines-guide.md
- references/kotlin-backend-patterns.md
- references/kotlin-coroutines-patterns.md
- references/kotlin-deployment.md
- references/kotlin-di-koin.md
- references/kotlin-flow-reactive.md
- references/kotlin-testing-mockk.md
- references/ktor-setup.md
FAQ
Что делает скилл kotlin-backend-patterns?
Use when the user asks about Koin DI, MockK tests, runTest coroutine testing, Kotlin repository and service layers, DTO mapping with extension functions or sealed error hierarchies. Produces Kotlin backend pattern code. Not for Ktor app structure (use kotlin-architecture) or Android (use android).
Как установить скилл kotlin-backend-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл kotlin-backend-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…