---
name: service-template-improvements
overview: "Make the service template production-ready: add testing, env management, DB scaffolding, auth, validation, docs and CI."
todos: []
---

# Improve Service Template (services/_template)

## Goal

Make `services/_template` production-ready and developer-friendly by adding testing infra, environment templates/validation, database scaffolding, auth & RBAC, request validation, API docs, standardized error handling, repository pattern, and CI. Changes should preserve existing structure and follow GoodGo project rules.

## High-level steps

1. Testing & CI

   - Add `jest.config.ts`, `setupTests.ts`, and example unit/integration tests for `FeatureService` and `HealthController`.
   - Add `supertest` based E2E test for `/health` and `/api/v1/features`.
   - Update `package.json` scripts to run tests and coverage.
   - Files: `services/_template/package.json`, add `jest.config.ts` at repo root of template, tests under `services/_template/src/__tests__/`.

2. Environment & Local Dev

   - Add `.env.example` and `.env.local.example` with all required vars (PORT, NODE_ENV, DATABASE_URL, REDIS_URL, JAEGER_ENDPOINT, TRACING_ENABLED, SERVICE_NAME, API_VERSION).
   - Enhance `src/config/app.config.ts` to accept `.env.local` overrides and document each var in `README.md`.
   - Files: `services/_template/.env.example`, `services/_template/.env.local.example`, `services/_template/src/config/app.config.ts`, `services/_template/README.md`.

3. Prisma & Database

   - Add `prisma/schema.prisma` example with a `Feature` model, and `prisma/seed.ts` placeholder.
   - Add migration/dev workflow to README and `package.json` scripts (`prisma:generate`, `prisma:migrate`, `prisma:seed`).
   - Files: `services/_template/prisma/schema.prisma`, `services/_template/prisma/seed.ts`, `services/_template/package.json` (scripts already partly present — document usage).

4. Authentication & Authorization

   - Add auth middleware `src/middlewares/auth.middleware.ts` using `@goodgo/auth-sdk` and JWT guards.
   - Add role-based decorator/utility and example protected route in `Feature` module.
   - Files: `services/_template/src/middlewares/auth.middleware.ts`, update `services/_template/src/routes/index.ts` and `services/_template/src/modules/feature/feature.module.ts`.

5. Request Validation & Sanitization

   - Add `validateDto` middleware that uses Zod DTOs (e.g., `createFeatureDtoSchema`) and integrates in `feature.module` routes.
   - Sanitize input (simple trimming) helper.
   - Files: `services/_template/src/middlewares/validation.middleware.ts`, update `src/modules/feature/feature.module.ts` to parse body.

6. API Documentation (OpenAPI)

   - Add OpenAPI spec generator (e.g., `openapi-typescript` or `swagger-jsdoc`) and `/docs` route serving Swagger UI.
   - Files: `services/_template/src/docs/openapi.ts`, `services/_template/src/routes/docs.ts`, update `README.md`.

7. Error Handling & Standard Errors

   - Introduce custom error classes (`src/errors/http-error.ts`, `src/errors/not-found.ts`, `src/errors/bad-request.ts`) and an `error-code` enum.
   - Ensure `error.middleware.ts` maps known errors to proper status codes and structured `ApiResponse`.
   - Files: `services/_template/src/errors/*.ts`, update `src/middlewares/error.middleware.ts`.

8. Repository Pattern & Transactions

   - Add `src/modules/common/repository.ts` scaffolding and update `FeatureService` to use repository and Prisma transactions for multi-step operations.
   - Files: `services/_template/src/modules/common/repository.ts`, update `services/_template/src/modules/feature/feature.service.ts`.

9. Observability Improvements

   - Ensure metrics registry reset in tests to avoid global state contamination.
   - Add correlation id middleware and attach trace ids to logs.
   - Files: `services/_template/src/middlewares/correlation.middleware.ts`, update `src/middlewares/logger.middleware.ts` and `src/main.ts` to add header mappings.

10. Docker & Image Best Practices

    - Add `.dockerignore` and ensure `NODE_ENV` build-time handling.
    - Make Docker build cache-friendly and document image tagging conventions in README.
    - Files: `services/_template/.dockerignore`, `services/_template/Dockerfile` (reviewed changes only documented).

11. Documentation & Examples

    - Update `README.md` with examples: local dev, running tests, generating Prisma client, environment explanation, and how to create a new service from template.
    - Add code comment examples showing bilingual comment pattern where new modules are introduced.

## Implementation details & snippets

- Example: Add DTO validation middleware and usage:
```typescript
// services/_template/src/middlewares/validation.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { AnyZodObject } from 'zod';

export const validateDto = (schema: AnyZodObject) => (req: Request, res: Response, next: NextFunction) => {
  try {
    req.body = schema.parse(req.body);
    return next();
  } catch (err: any) {
    return res.status(400).json({ success: false, error: { code: 'VALIDATION_ERROR', message: err.message } });
  }
};
```

- Example: Custom HTTP error mapping in `error.middleware.ts` — convert `HttpError` to proper status and code.

- Tests: Add `src/__tests__/health.e2e.ts` using `supertest` to assert readiness/liveness and metrics endpoint.

## Todos (for tracking)

- setup-tests: Add Jest config, test utilities, and example tests.
- add-dotenv-examples: Add `.env.example` and `.env.local.example` and document envs in README.
- prisma-scaffold: Add `prisma/schema.prisma` and `prisma/seed.ts` with Feature model.
- auth-middleware: Implement auth middleware & RBAC utilities and protect example route.
- validation-middleware: Implement Zod validation middleware and apply to feature routes.
- openapi: Add OpenAPI generation and Swagger UI route.
- errors: Implement custom error classes and improve `error.middleware` mapping.
- repository-pattern: Add repository scaffolding and update FeatureService.
- observability: Add correlation id middleware and test-safe prom-client usage.
- docker-ci: Add .dockerignore and document Docker improvements in README.
- docs: Update README and ARCHITECTURE.md with new instructions.

Each todo will contain detailed substeps when started.

## Time estimates (rough)

- High priority set (tests, env, prisma, validation, auth): 2–4 days
- Medium (openapi, errors, repo pattern): 1–2 days
- Low (docker polish, extra docs): 0.5–1 day

## Next step

If you approve, I will generate a concrete implementation plan and break the top-priority todos into file-level patches. If you prefer a different priority (e.g., focus on Auth first), tell me which to prioritize.