refactor(nest): migrate tagService into TagsService DI (pilot)

Move the tag SQL from src/services/tagService.ts into TagsService over an
injected DatabaseService (identical statements, #10b981 default, COALESCE
semantics). Non-Nest consumers (MCP tools, plugin RPC host) go through the
new tags.bridge.ts, which exports the legacy function names 1:1 from a
module-level instance over the shared db Proxy — the settled pattern for
the remaining legacy-service migrations (recipe documented in
src/nest/README.md). Tests are DI-native: direct service construction in
unit (with bridge delegation cases for the coverage gate) and
DatabaseModule + real SQL in e2e.
This commit is contained in:
jubnl
2026-07-25 18:36:17 +02:00
parent dd2c2d6668
commit 53e884ad55
9 changed files with 260 additions and 120 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { isDemoUser } from '../../services/authService';
import { listTags, createTag, getTagByIdAndUser, updateTag, deleteTag } from '../../services/tagService';
import { listTags, createTag, getTagByIdAndUser, updateTag, deleteTag } from '../../nest/tags/tags.bridge';
import {
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+49
View File
@@ -26,6 +26,8 @@ mount to Nest and leaves the sibling trip routes (days, places, ...) on Express.
- **Phase 1 (leaf):** weather, airports, config (public), system-notices, maps,
categories, tags, notifications, atlas.
- **Phase 2 (trip sub-domains):** vacay (addon), packing, todo.
- **DI-native services (legacy `src/services/*` deleted):** tags — see the
migration recipe below.
## Cross-cutting Foundation pieces
@@ -88,3 +90,50 @@ validation/error parity → unit + parity + e2e tests over the gate → prefix t
Nest → parity verified on the demo DB → **then** decommission the old Express
route/service (separate step, after the toggle is confirmed in prod) → frontend points
at the typed contract (Frontend Track).
## Migrating a legacy `src/services/*` service into its Nest module (recipe)
Pilot: **tags** (`services/tagService.ts` → `nest/tags/tags.service.ts` +
`nest/tags/tags.bridge.ts`). Repeat these steps per service (next up:
categoryService, then todoService). This is a **pure relocation** — byte-identical
SQL, statuses, bodies, and error strings.
1. **Move the SQL** into `<domain>.service.ts` as methods over an injected
`DatabaseService` (`this.db.all<T>/get<T>/run/prepare/transaction`; strict
constructor injection, no `@Optional()`). Preserve every quirk: falsy-coercion
defaults (`x || fallback`, never `??`), post-insert/post-update re-selects (no
RETURNING), `COALESCE` semantics. If a controller already wraps the legacy
functions, do not change the service's method surface. The module needs no
`imports: [DatabaseModule]` — it's `@Global`.
2. **Add `<domain>.bridge.ts`** next to the service **only if non-Nest consumers
exist** (MCP tools, plugin RPC host, scheduler, websocket). It builds a
module-level instance over the shared connection Proxy —
`new XService(new DatabaseService(db))`, reinitialize-proof, same pattern as
`plugins/host/create-rpc-host.ts` — and exports the legacy function names 1:1.
Container code injects the service; only outside-container code imports the
bridge. *(Design decision, settled with the tags pilot: MCP tools stay outside
the container and use the bridge. The alternative — handing the Nest app to the
MCP layer via `app.get(XService)` — was rejected: it would thread the container
through `mcpHandler` + every tool registrar and force a Nest bootstrap into the
container-less `tests/helpers/mcp-harness.ts` used by ~25 MCP suites.)*
3. **Repoint non-Nest consumers** — import-path-only diffs from
`services/<x>Service` to `nest/<domain>/<domain>.bridge`; call sites unchanged.
4. **Delete the legacy service** once `grep -rn "services/<x>Service" src tests`
only hits the tests you're rewriting.
5. **Tests:**
- Move `tests/unit/services/<x>Service.test.ts` →
`tests/unit/nest/<domain>.service.test.ts`, preserving case IDs. Construct the
service directly — `new XService(new DatabaseService(testDb))` — no
TestingModule, no `overrideProvider` (repo convention). Add one delegation
case per bridge export: the bridge sits under `src/nest/**`, inside the ≥80%
coverage gate, and these cases pin it deterministically.
- Convert the module e2e to the DI-native pattern (exemplar
`tests/e2e/trips.e2e.test.ts`): temp-db DDL for the domain's tables,
`imports: [DatabaseModule, <Domain>Module]`, real SQL assertions. Keep only
the `vi.mock('../../src/db/database', …)` — the auth guard still reads users
through the singleton, and `DatabaseModule`'s factory picks up the same
mocked db. Drop the legacy-service mock entirely.
- Suites that mocked the legacy module (e.g. `create-rpc-host.test.ts`) mock
the bridge path instead — same factory shape, path-only change.
6. **Verify** (from `server/`): `npm run typecheck`, `test:unit`,
`test:integration`, `test:e2e`, `lint:check`, `test:coverage`.
@@ -7,7 +7,7 @@ import { listItems as listPackingItemsSvc, createItem as createPackingItemSvc, u
import { isUpdateConflict } from '../../../services/conflictResult';
import { getWeather } from '../../../services/weatherService';
import { listCategories } from '../../../services/categoryService';
import { listTags, createTag, updateTag, deleteTag, getTagByIdAndUser } from '../../../services/tagService';
import { listTags, createTag, updateTag, deleteTag, getTagByIdAndUser } from '../../tags/tags.bridge';
import { listItems as listTodosSvc, createItem as createTodoSvc, updateItem as updateTodoSvc, deleteItem as deleteTodoSvc } from '../../../services/todoService';
import { listFiles, createFile, createFileLink, getFileById, updateFile, softDeleteFile, findForeignLinkTarget, resolveFilePath, BLOCKED_EXTENSIONS, filesDir } from '../../../services/fileService';
import { createNote as createCollabNoteSvc, createPoll as createCollabPollSvc, votePoll as voteCollabPollSvc, createMessage as createCollabMessageSvc, listNotes as listCollabNotesSvc, listPolls as listCollabPollsSvc, listMessages as listCollabMessagesSvc } from '../../../services/collabService';
+36
View File
@@ -0,0 +1,36 @@
import type { Tag } from '@trek/shared';
import { db } from '../../db/database';
import { DatabaseService } from '../database/database.service';
import { TagsService } from './tags.service';
/**
* Non-Nest entry point for the tags domain — for code running OUTSIDE the Nest
* container (MCP tools, plugin RPC host). Exports the legacy
* services/tagService function names 1:1 so repointing a consumer is an
* import-path-only diff. Inside the container, inject TagsService instead.
*
* Module-level construction is safe: `db` is the reinitialize-proof Proxy onto
* the shared better-sqlite3 singleton (same pattern as
* plugins/host/create-rpc-host.ts).
*/
const tags = new TagsService(new DatabaseService(db));
export function listTags(userId: number): Tag[] {
return tags.list(userId);
}
export function createTag(userId: number, name: string, color?: string): Tag {
return tags.create(userId, name, color);
}
export function getTagByIdAndUser(tagId: number | string, userId: number): Tag | undefined {
return tags.getByIdAndUser(tagId, userId);
}
export function updateTag(tagId: number | string, name?: string, color?: string): Tag | undefined {
return tags.update(tagId, name, color);
}
export function deleteTag(tagId: number | string): void {
tags.remove(tagId);
}
+24 -14
View File
@@ -1,36 +1,46 @@
import { Injectable } from '@nestjs/common';
import type { Tag } from '@trek/shared';
import {
listTags,
createTag,
getTagByIdAndUser,
updateTag,
deleteTag,
} from '../../services/tagService';
import { DatabaseService } from '../database/database.service';
/**
* Thin Nest wrapper around the existing tag service. Ownership scoping and the
* default colour fallback stay in tagService, so behaviour is unchanged.
* Tags domain service — owns the tag SQL (moved 1:1 from the legacy
* services/tagService.ts: identical statements, the #10b981 default and the
* COALESCE update semantics). Non-Nest consumers (MCP tools, plugin RPC host)
* go through tags.bridge.ts instead of importing this class directly.
*/
@Injectable()
export class TagsService {
constructor(private readonly db: DatabaseService) {}
list(userId: number): Tag[] {
return listTags(userId) as Tag[];
return this.db.all<Tag>('SELECT * FROM tags WHERE user_id = ? ORDER BY name ASC', userId);
}
getByIdAndUser(id: string | number, userId: number): Tag | undefined {
return getTagByIdAndUser(id, userId) as Tag | undefined;
return this.db.get<Tag>('SELECT * FROM tags WHERE id = ? AND user_id = ?', id, userId);
}
create(userId: number, name: string, color?: string): Tag {
return createTag(userId, name, color) as Tag;
const result = this.db.run(
'INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)',
userId,
name,
color || '#10b981',
);
return this.db.get<Tag>('SELECT * FROM tags WHERE id = ?', result.lastInsertRowid) as Tag;
}
update(id: string | number, name?: string, color?: string): Tag {
return updateTag(id, name, color) as Tag;
this.db.run(
'UPDATE tags SET name = COALESCE(?, name), color = COALESCE(?, color) WHERE id = ?',
name || null,
color || null,
id,
);
return this.db.get<Tag>('SELECT * FROM tags WHERE id = ?', id) as Tag;
}
remove(id: string | number): void {
deleteTag(id);
this.db.run('DELETE FROM tags WHERE id = ?', id);
}
}
-26
View File
@@ -1,26 +0,0 @@
import { db } from '../db/database';
export function listTags(userId: number) {
return db.prepare('SELECT * FROM tags WHERE user_id = ? ORDER BY name ASC').all(userId);
}
export function createTag(userId: number, name: string, color?: string) {
const result = db.prepare(
'INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)'
).run(userId, name, color || '#10b981');
return db.prepare('SELECT * FROM tags WHERE id = ?').get(result.lastInsertRowid);
}
export function getTagByIdAndUser(tagId: number | string, userId: number) {
return db.prepare('SELECT * FROM tags WHERE id = ? AND user_id = ?').get(tagId, userId);
}
export function updateTag(tagId: number | string, name?: string, color?: string) {
db.prepare('UPDATE tags SET name = COALESCE(?, name), color = COALESCE(?, color) WHERE id = ?')
.run(name || null, color || null, tagId);
return db.prepare('SELECT * FROM tags WHERE id = ?').get(tagId);
}
export function deleteTag(tagId: number | string) {
db.prepare('DELETE FROM tags WHERE id = ?').run(tagId);
}