refactor(media)!: delete media demo feature
Veect retrofit (ADR-027): third slice of the demo-content removal. Deletes packages/media whole and prunes every composition edge in one commit: core-api router mount + dep, core-cms collection composition + dep + regenerated Payload types, web-next bindAll (prod + dev-seed) + tests + Tailwind source + transpilePackages + dep, cms/core-cms/web-next payload config test assertions, tsconfig paths, anchor-guard + generator e2e feature lists, compliance data-map + retention-policy regeneration, lockfile prune, and feature-list doc entries (CLAUDE.md, AGENTS.md, glossary, app/feature AGENTS.md). Media was the uploads feature: the marketing-pages pages.hero.image and navigation header.logo upload fields (relationTo: "media") are removed from those collections in this slice — Payload config sanitization rejects a relationship to a missing collection. Both features' domain entities keep their optional imageId/logoId fields; their repositories already tolerate the fields being absent. Both features are deleted in later slices. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016j8z4VHjedXDTjEDNg7qHK
This commit is contained in:
14
AGENTS.md
14
AGENTS.md
@@ -37,7 +37,6 @@ See `docs/guides/runbook.md` for the full workflow.
|
||||
| `@repo/core-cms` | core-composition | Payload config aggregator — imports `@repo/<feature>/cms` only |
|
||||
| `@repo/core-trpc` | core-composition | Frontend tRPC client + framework-specific providers (Next.js, TanStack) |
|
||||
| `@repo/auth` | feature | Users collection + sign-in/up/out |
|
||||
| `@repo/media` | feature | Media collection + upload helpers |
|
||||
| `@repo/marketing-pages` | feature | Pages collection + SiteSettings global |
|
||||
| `@repo/navigation` | feature | Header global |
|
||||
| `@repo/core-eslint` | tooling | Shared ESLint 9 flat configs (base, next, react-internal, boundaries) |
|
||||
@@ -53,7 +52,7 @@ See `docs/guides/runbook.md` for the full workflow.
|
||||
- **app** (3 packages) — `apps/web-next`, `apps/cms`, `apps/storybook`
|
||||
- **core-composition** (3 packages) — `packages/core-api`, `core-cms`, `core-trpc`
|
||||
- **core** (1–2 packages) — `packages/core-shared`; `core-ui` is optional (scaffold with `pnpm turbo gen core-package ui`)
|
||||
- **feature** (4 packages) — `packages/auth`, `media`, `marketing-pages`, `navigation`
|
||||
- **feature** (3 packages) — `packages/auth`, `marketing-pages`, `navigation`
|
||||
- **tooling** (3 packages) — `packages/core-eslint`, `core-typescript`, `core-testing`
|
||||
|
||||
### Allowed dependency directions
|
||||
@@ -228,7 +227,7 @@ export const getArticlesUseCase =
|
||||
};
|
||||
```
|
||||
|
||||
Void-input use cases use `z.object({}).strict()` and accept `_input: XInput`. Void-output use cases (e.g. `signOutUseCase`, `deleteMediaUseCase`) export only `xInputSchema` — no `xOutputSchema`.
|
||||
Void-input use cases use `z.object({}).strict()` and accept `_input: XInput`. Void-output use cases (e.g. `signOutUseCase`) export only `xInputSchema` — no `xOutputSchema`.
|
||||
|
||||
Tests inject mocks directly — no container rebinding:
|
||||
|
||||
@@ -268,7 +267,7 @@ export const getArticlesController =
|
||||
};
|
||||
```
|
||||
|
||||
Void controllers (e.g. `signOutController`, `deleteMediaController`) return `Promise<void>` and skip the presenter entirely. One controller file per use case — no multi-method controller files.
|
||||
Void controllers (e.g. `signOutController`) return `Promise<void>` and skip the presenter entirely. One controller file per use case — no multi-method controller files.
|
||||
|
||||
DI binds each factory with `.toDynamicValue()`:
|
||||
|
||||
@@ -386,7 +385,6 @@ export async function bindAllProduction(): Promise<void> {
|
||||
bindProductionAuth(ctx);
|
||||
bindProductionMarketingPages(ctx);
|
||||
bindProductionNavigation(ctx);
|
||||
bindProductionMedia(ctx);
|
||||
}
|
||||
|
||||
export async function bindAllDevSeed(): Promise<void> {
|
||||
@@ -406,11 +404,11 @@ export async function bindAllDevSeed(): Promise<void> {
|
||||
};
|
||||
|
||||
await bindDevSeedAuth(ctx);
|
||||
// ... (same for marketing-pages, navigation, media)
|
||||
// ... (same for marketing-pages, navigation)
|
||||
}
|
||||
```
|
||||
|
||||
Actual function names: `bindProductionAuth`, `bindProductionMarketingPages`, `bindProductionNavigation`, `bindProductionMedia`.
|
||||
Actual function names: `bindProductionAuth`, `bindProductionMarketingPages`, `bindProductionNavigation`.
|
||||
|
||||
Each feature binder signature is `(ctx: BindProductionContext): void` for production and `(ctx: BindContext): Promise<void>` for dev-seed. Required ctx fields: `tracer`, `logger`. Production-only: `config`. Optional: `bus`, `queue`, `realtime`, `realtimeRegistry`.
|
||||
|
||||
@@ -576,6 +574,6 @@ Per-package documentation lives in each `AGENTS.md`:
|
||||
- `packages/core-shared/AGENTS.md`
|
||||
- `packages/core-api/AGENTS.md`, `core-cms/AGENTS.md`, `core-trpc/AGENTS.md`
|
||||
- `packages/core-ui/AGENTS.md` (optional — generated by `pnpm turbo gen core-package ui`; see `turbo/generators/templates/core-package/ui/AGENTS.md.hbs`)
|
||||
- `packages/auth/AGENTS.md`, `media/AGENTS.md`, `marketing-pages/AGENTS.md`, `navigation/AGENTS.md`
|
||||
- `packages/auth/AGENTS.md`, `marketing-pages/AGENTS.md`, `navigation/AGENTS.md`
|
||||
- `packages/core-eslint/AGENTS.md`, `core-typescript/AGENTS.md`, `core-testing/AGENTS.md`
|
||||
- `apps/cms/AGENTS.md`, `web-next/AGENTS.md`, `storybook/AGENTS.md`
|
||||
|
||||
@@ -44,7 +44,7 @@ See `docs/guides/tdd-workflow.md` for the full cycle.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Turborepo + pnpm monorepo organized by vertical features. Each feature (`auth`, `media`, `marketing-pages`, `navigation`) owns its Clean Architecture layers. Must-have core packages (`core-shared`, `core-cms`, `core-api`) provide foundation; five optional core packages (`core-realtime`, `core-events`, `core-trpc`, `core-ui`, `core-audit`) scaffold on demand via `pnpm turbo gen core-package <name>` (see `docs/architecture/template-tiers.md`). Two tooling packages (`core-eslint`, `core-typescript`) provide shared configs. Workspace boundaries are enforced by ESLint (lint-time) and Turborepo (build-graph time). Supports Next.js and TanStack Start as frontend frameworks, Payload CMS for content management, and comprehensive agent-optimized documentation.
|
||||
Turborepo + pnpm monorepo organized by vertical features. Each feature (`auth`, `marketing-pages`, `navigation`) owns its Clean Architecture layers. Must-have core packages (`core-shared`, `core-cms`, `core-api`) provide foundation; five optional core packages (`core-realtime`, `core-events`, `core-trpc`, `core-ui`, `core-audit`) scaffold on demand via `pnpm turbo gen core-package <name>` (see `docs/architecture/template-tiers.md`). Two tooling packages (`core-eslint`, `core-typescript`) provide shared configs. Workspace boundaries are enforced by ESLint (lint-time) and Turborepo (build-graph time). Supports Next.js and TanStack Start as frontend frameworks, Payload CMS for content management, and comprehensive agent-optimized documentation.
|
||||
|
||||
## Read First
|
||||
|
||||
@@ -95,7 +95,7 @@ See `docs/guides/coverage.md` for the cookbook and ADR-020 for the full rational
|
||||
## Key Conventions
|
||||
|
||||
- **Conventional Commits (non-negotiable)** — Every commit message MUST follow the [Conventional Commits](https://www.conventionalcommits.org/) spec: `<type>(<scope>): <imperative subject>` (≤72 chars). Types: `feat | fix | docs | style | refactor | test | chore | perf | ci | build | revert`. Use `!` after type/scope for breaking changes. Body explains WHY if non-obvious. Examples: `feat(auth): hash password before persisting`, `test(blog): assert article not found error`, `refactor(docs)!: consolidate scaffolding into guides`. The sandcastle implementer + reviewer prompts both enforce this; agents authoring commits autonomously MUST honor it. Commits become versions + changelog entries automatically via release-please (ADR-021 / `docs/guides/releasing.md`).
|
||||
- **Versioning is hybrid (ADR-021)** — Root template (`template-vertical`) + 4 feature packages (`@repo/{auth,media,marketing-pages,navigation}`) each version independently from `0.1.0`. release-please reads Conventional Commits since the last tag and opens a rolling release PR on every merge to main; merging it cuts per-package tags (`template-v0.2.0`, `auth-v0.1.1`, etc.) + GitHub releases. **Bump targeting is by commit path** — files under `packages/<feature>/**` bump that feature; cross-cutting paths (`docs/`, `scripts/`, `.github/`, root configs) bump the root. Pre-1.0 policy: `feat:` → patch, `feat!:` → minor.
|
||||
- **Versioning is hybrid (ADR-021)** — Root template (`template-vertical`) + 3 feature packages (`@repo/{auth,marketing-pages,navigation}`) each version independently from `0.1.0`. release-please reads Conventional Commits since the last tag and opens a rolling release PR on every merge to main; merging it cuts per-package tags (`template-v0.2.0`, `auth-v0.1.1`, etc.) + GitHub releases. **Bump targeting is by commit path** — files under `packages/<feature>/**` bump that feature; cross-cutting paths (`docs/`, `scripts/`, `.github/`, root configs) bump the root. Pre-1.0 policy: `feat:` → patch, `feat!:` → minor.
|
||||
- **Relative imports in `src/`** — Source files use relative paths (`../repositories/...`), not `@/` alias
|
||||
- **`@/` alias in tests** — Test files (`*.test.ts`) use `@/` to import from `src/`
|
||||
- **`vitest.config.ts`** — Every package must define `resolve.alias: { "@": path.resolve(__dirname, "./src") }`
|
||||
|
||||
@@ -5,7 +5,7 @@ describe("CMS app payload.config", () => {
|
||||
it("registers all feature collections", async () => {
|
||||
const resolved = await config;
|
||||
const slugs = resolved.collections?.map((c) => c.slug) ?? [];
|
||||
expect(slugs).toEqual(expect.arrayContaining(["users", "pages", "media"]));
|
||||
expect(slugs).toEqual(expect.arrayContaining(["users", "pages"]));
|
||||
});
|
||||
|
||||
it("registers all feature globals", async () => {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -67,11 +67,11 @@ export function Providers({ children }: { children: React.ReactNode }) {
|
||||
## Dependencies
|
||||
|
||||
| Dependency | Purpose |
|
||||
| --------------------------------- | ---------------------------------------------------------- |
|
||||
| -------------------------------------- | ---------------------------------------------------------- |
|
||||
| `@repo/core-api` | `appRouter` for tRPC endpoint |
|
||||
| `@repo/core-trpc/next` | Next.js tRPC client + provider (optional — scaffold first) |
|
||||
| `@repo/core-ui` | Design system components (optional — scaffold first) |
|
||||
| `@repo/auth`, `@repo/media`, etc. | Feature packages (indirectly via core-api) |
|
||||
| `@repo/auth`, `@repo/navigation`, etc. | Feature packages (indirectly via core-api) |
|
||||
| `next` | Next.js 15 framework |
|
||||
| `@trpc/server` | tRPC server (fetch adapter) |
|
||||
|
||||
@@ -104,7 +104,7 @@ Run: `pnpm test:e2e` starts the dev server and runs all `.spec.ts` files.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- **Feature packages:** `packages/{auth,media,marketing-pages,navigation}/`
|
||||
- **Feature packages:** `packages/{auth,marketing-pages,navigation}/`
|
||||
- **tRPC composition:** `packages/core-api/AGENTS.md`
|
||||
- **tRPC client + provider (optional):** scaffold `@repo/core-trpc` first, then see `turbo/generators/templates/core-package/trpc/AGENTS.md.hbs`
|
||||
- **UI components (optional):** scaffold with `pnpm turbo gen core-package ui`, then see `turbo/generators/templates/core-package/ui/AGENTS.md.hbs`
|
||||
|
||||
@@ -13,7 +13,6 @@ const nextConfig = {
|
||||
"@repo/core-shared",
|
||||
"@repo/core-ui",
|
||||
"@repo/marketing-pages",
|
||||
"@repo/media",
|
||||
"@repo/navigation",
|
||||
"@repo/core-trpc",
|
||||
],
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
"@repo/core-shared": "workspace:*",
|
||||
"@repo/core-trpc": "workspace:^",
|
||||
"@repo/marketing-pages": "workspace:*",
|
||||
"@repo/media": "workspace:*",
|
||||
"@repo/navigation": "workspace:*",
|
||||
"@sentry/nextjs": "^10.51.0",
|
||||
"@tailwindcss/postcss": "^4.3.0",
|
||||
|
||||
@@ -13,9 +13,6 @@ vi.mock("@repo/marketing-pages/di/bind-production", () => ({
|
||||
vi.mock("@repo/navigation/di/bind-production", () => ({
|
||||
bindProductionNavigation: vi.fn(),
|
||||
}));
|
||||
vi.mock("@repo/media/di/bind-production", () => ({
|
||||
bindProductionMedia: vi.fn(),
|
||||
}));
|
||||
vi.mock("@repo/auth/di/bind-dev-seed", () => ({ bindDevSeedAuth: vi.fn() }));
|
||||
vi.mock("@repo/marketing-pages/di/bind-dev-seed", () => ({
|
||||
bindDevSeedMarketingPages: vi.fn(),
|
||||
@@ -23,7 +20,6 @@ vi.mock("@repo/marketing-pages/di/bind-dev-seed", () => ({
|
||||
vi.mock("@repo/navigation/di/bind-dev-seed", () => ({
|
||||
bindDevSeedNavigation: vi.fn(),
|
||||
}));
|
||||
vi.mock("@repo/media/di/bind-dev-seed", () => ({ bindDevSeedMedia: vi.fn() }));
|
||||
vi.mock("@repo/core-shared/instrumentation", async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import("@repo/core-shared/instrumentation")>();
|
||||
@@ -43,7 +39,7 @@ describe("bindAllProduction", () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("binds all four feature production repos", async () => {
|
||||
it("binds all three feature production repos", async () => {
|
||||
const { bindAllProduction } = await import("./bind-production");
|
||||
const { bindProductionAuth } =
|
||||
await import("@repo/auth/di/bind-production");
|
||||
@@ -51,15 +47,12 @@ describe("bindAllProduction", () => {
|
||||
await import("@repo/marketing-pages/di/bind-production");
|
||||
const { bindProductionNavigation } =
|
||||
await import("@repo/navigation/di/bind-production");
|
||||
const { bindProductionMedia } =
|
||||
await import("@repo/media/di/bind-production");
|
||||
|
||||
await bindAllProduction();
|
||||
|
||||
expect(bindProductionAuth).toHaveBeenCalledOnce();
|
||||
expect(bindProductionMarketingPages).toHaveBeenCalledOnce();
|
||||
expect(bindProductionNavigation).toHaveBeenCalledOnce();
|
||||
expect(bindProductionMedia).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("is idempotent via bindAll — second call does not re-bind", async () => {
|
||||
|
||||
@@ -20,11 +20,9 @@ import { NoopRateLimit } from "@repo/core-shared/rate-limit";
|
||||
import { bindProductionAuth } from "@repo/auth/di/bind-production";
|
||||
import { bindProductionMarketingPages } from "@repo/marketing-pages/di/bind-production";
|
||||
import { bindProductionNavigation } from "@repo/navigation/di/bind-production";
|
||||
import { bindProductionMedia } from "@repo/media/di/bind-production";
|
||||
import { bindDevSeedAuth } from "@repo/auth/di/bind-dev-seed";
|
||||
import { bindDevSeedMarketingPages } from "@repo/marketing-pages/di/bind-dev-seed";
|
||||
import { bindDevSeedNavigation } from "@repo/navigation/di/bind-dev-seed";
|
||||
import { bindDevSeedMedia } from "@repo/media/di/bind-dev-seed";
|
||||
|
||||
let bindPromise: Promise<void> | null = null;
|
||||
|
||||
@@ -100,7 +98,6 @@ export async function bindAllProduction(): Promise<void> {
|
||||
bindProductionAuth(ctx);
|
||||
bindProductionMarketingPages(ctx);
|
||||
bindProductionNavigation(ctx);
|
||||
bindProductionMedia(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,7 +119,6 @@ export async function bindAllDevSeed(): Promise<void> {
|
||||
await bindDevSeedAuth(ctx);
|
||||
await bindDevSeedMarketingPages(ctx);
|
||||
await bindDevSeedNavigation(ctx);
|
||||
await bindDevSeedMedia(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
@source "../../../../packages/core-ui/src";
|
||||
@source "../../../../packages/navigation/src";
|
||||
@source "../../../../packages/marketing-pages/src";
|
||||
@source "../../../../packages/media/src";
|
||||
@source "../../../../packages/auth/src";
|
||||
@source "../";
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,10 +2,6 @@
|
||||
# Generated by scripts/compliance/emit-data-map.mjs — do not edit manually.
|
||||
# Run `pnpm compliance:data-map` to regenerate.
|
||||
collections:
|
||||
media:
|
||||
auth: false
|
||||
piiFields: []
|
||||
slug: media
|
||||
pages:
|
||||
auth: false
|
||||
piiFields: []
|
||||
|
||||
@@ -2,13 +2,6 @@
|
||||
# Generated by scripts/compliance/emit-retention-policy.mjs — do not edit manually.
|
||||
# Run `pnpm compliance:retention-policy` to regenerate.
|
||||
collections:
|
||||
media:
|
||||
postDeletion:
|
||||
action: hard-delete
|
||||
duration: P90D
|
||||
trigger: after-deletion
|
||||
purgeSchedule: monthly
|
||||
slug: media
|
||||
pages:
|
||||
postDeletion:
|
||||
action: hard-delete
|
||||
|
||||
@@ -22,7 +22,7 @@ _Avoid:_ module, library, app (unless specifically `apps/`).
|
||||
The boundary classification on a package (`app`, `core`, `core-composition`, `feature`, `tooling`). Enforced by ESLint (`eslint-plugin-boundaries`) and Turborepo `boundaries`. See `AGENTS.md` → Boundary Rules.
|
||||
|
||||
**Feature** (a.k.a. **feature package**):
|
||||
A vertical slice owning its Clean Architecture layers + integrations under `packages/<name>/`. Currently: `auth`, `media`, `marketing-pages`, `navigation`. **In architecture-refactor conversations (the `improve-codebase-architecture` skill), "module" defaults to "feature" — they're the same unit at the highest level of granularity.**
|
||||
A vertical slice owning its Clean Architecture layers + integrations under `packages/<name>/`. Currently: `auth`, `marketing-pages`, `navigation`. **In architecture-refactor conversations (the `improve-codebase-architecture` skill), "module" defaults to "feature" — they're the same unit at the highest level of granularity.**
|
||||
_Avoid:_ domain, vertical (use "feature" or "vertical feature"). "Module" is acceptable inside the refactor skill specifically, where it abstractly covers "anything with interface + implementation" at any scale (use case, controller, repository port, or full feature).
|
||||
|
||||
**Must-have core**:
|
||||
@@ -190,7 +190,7 @@ The commit-message spec mandated by this template — `<type>(<scope>): <imperat
|
||||
The Google-maintained automation that reads Conventional Commits, derives semver bumps, and opens a rolling release PR with version bumps + per-package CHANGELOG entries on every push to main. Configured in `release-please-config.json` + `.release-please-manifest.json`. ADR-021.
|
||||
|
||||
**Hybrid versioning**:
|
||||
The template's versioning strategy (ADR-021) — root template (`template-vertical`) + 4 feature packages (`@repo/{auth,media,marketing-pages,navigation}`) version independently from `0.1.0`. Core packages, tooling, and apps are NOT versioned (cascade-effect would invalidate the signal).
|
||||
The template's versioning strategy (ADR-021) — root template (`template-vertical`) + 3 feature packages (`@repo/{auth,marketing-pages,navigation}`) version independently from `0.1.0`. Core packages, tooling, and apps are NOT versioned (cascade-effect would invalidate the signal).
|
||||
|
||||
**Tag prefix**:
|
||||
The per-package prefix release-please uses to avoid tag collisions in a monorepo — `template-v0.1.0` for the root, `auth-v0.1.0` / etc. for features.
|
||||
|
||||
@@ -151,7 +151,7 @@ tests/
|
||||
|
||||
## What it must NOT import
|
||||
|
||||
- Any other feature package (`@repo/blog`, `@repo/media`, etc.)
|
||||
- Any other feature package (`@repo/marketing-pages`, `@repo/navigation`, etc.)
|
||||
- Any app package
|
||||
- `@repo/core-api`, `@repo/core-cms`, `@repo/core-trpc`, `@repo/core-ui` directly; only `@repo/core-shared`
|
||||
> Note: `@repo/core-trpc` and `@repo/core-ui` are optional packages scaffolded via `pnpm turbo gen core-package trpc` / `ui`. If not present, these constraints still apply to any future installation.
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
"@repo/core-dsr": "workspace:*",
|
||||
"@repo/core-shared": "workspace:*",
|
||||
"@repo/marketing-pages": "workspace:*",
|
||||
"@repo/media": "workspace:*",
|
||||
"@repo/navigation": "workspace:*",
|
||||
"@trpc/server": "^11.0.0"
|
||||
},
|
||||
|
||||
@@ -2,7 +2,6 @@ import { router } from "@repo/core-shared/trpc/init";
|
||||
import { authRouter } from "@repo/auth/api";
|
||||
import { marketingPagesRouter } from "@repo/marketing-pages/api";
|
||||
import { navigationRouter } from "@repo/navigation/api";
|
||||
import { mediaRouter } from "@repo/media/api";
|
||||
import { dsrRouter } from "@repo/core-dsr";
|
||||
import { consentRouter } from "@repo/core-consent";
|
||||
|
||||
@@ -10,7 +9,6 @@ export const appRouter = router({
|
||||
auth: authRouter,
|
||||
marketingPages: marketingPagesRouter,
|
||||
navigation: navigationRouter,
|
||||
media: mediaRouter,
|
||||
// gen:routers — optional-core routers composed below
|
||||
dsr: dsrRouter,
|
||||
consent: consentRouter,
|
||||
|
||||
@@ -65,13 +65,12 @@ function makeUnauthCaller(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("appRouter composition", () => {
|
||||
it("exposes auth, marketingPages, navigation, media routers", () => {
|
||||
it("exposes auth, marketingPages, navigation routers", () => {
|
||||
const procedures = appRouter._def.procedures;
|
||||
const keys = Object.keys(procedures);
|
||||
expect(keys.some((k) => k.startsWith("auth."))).toBe(true);
|
||||
expect(keys.some((k) => k.startsWith("marketingPages."))).toBe(true);
|
||||
expect(keys.some((k) => k.startsWith("navigation."))).toBe(true);
|
||||
expect(keys.some((k) => k.startsWith("media."))).toBe(true);
|
||||
});
|
||||
|
||||
it("exposes dsr and consent routers", () => {
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
"@payloadcms/richtext-lexical": "^3.14.0",
|
||||
"@repo/auth": "workspace:*",
|
||||
"@repo/marketing-pages": "workspace:*",
|
||||
"@repo/media": "workspace:*",
|
||||
"@repo/navigation": "workspace:*",
|
||||
"payload": "^3.14.0"
|
||||
},
|
||||
|
||||
@@ -69,7 +69,6 @@ export interface Config {
|
||||
collections: {
|
||||
users: User;
|
||||
pages: Page;
|
||||
media: Media;
|
||||
"payload-kv": PayloadKv;
|
||||
"payload-locked-documents": PayloadLockedDocument;
|
||||
"payload-preferences": PayloadPreference;
|
||||
@@ -79,7 +78,6 @@ export interface Config {
|
||||
collectionsSelect: {
|
||||
users: UsersSelect<false> | UsersSelect<true>;
|
||||
pages: PagesSelect<false> | PagesSelect<true>;
|
||||
media: MediaSelect<false> | MediaSelect<true>;
|
||||
"payload-kv": PayloadKvSelect<false> | PayloadKvSelect<true>;
|
||||
"payload-locked-documents":
|
||||
| PayloadLockedDocumentsSelect<false>
|
||||
@@ -181,7 +179,6 @@ export interface Page {
|
||||
hero: {
|
||||
heading: string;
|
||||
subheading?: string | null;
|
||||
image?: (number | null) | Media;
|
||||
};
|
||||
layout?:
|
||||
| {
|
||||
@@ -203,25 +200,6 @@ export interface Page {
|
||||
createdAt: string;
|
||||
_status?: ("draft" | "published") | null;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "media".
|
||||
*/
|
||||
export interface Media {
|
||||
id: number;
|
||||
alt: string;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
url?: string | null;
|
||||
thumbnailURL?: string | null;
|
||||
filename?: string | null;
|
||||
mimeType?: string | null;
|
||||
filesize?: number | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
focalX?: number | null;
|
||||
focalY?: number | null;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "payload-kv".
|
||||
@@ -253,10 +231,6 @@ export interface PayloadLockedDocument {
|
||||
| ({
|
||||
relationTo: "pages";
|
||||
value: number | Page;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: "media";
|
||||
value: number | Media;
|
||||
} | null);
|
||||
globalSlug?: string | null;
|
||||
user: {
|
||||
@@ -337,7 +311,6 @@ export interface PagesSelect<T extends boolean = true> {
|
||||
| {
|
||||
heading?: T;
|
||||
subheading?: T;
|
||||
image?: T;
|
||||
};
|
||||
layout?:
|
||||
| T
|
||||
@@ -364,24 +337,6 @@ export interface PagesSelect<T extends boolean = true> {
|
||||
createdAt?: T;
|
||||
_status?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "media_select".
|
||||
*/
|
||||
export interface MediaSelect<T extends boolean = true> {
|
||||
alt?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
url?: T;
|
||||
thumbnailURL?: T;
|
||||
filename?: T;
|
||||
mimeType?: T;
|
||||
filesize?: T;
|
||||
width?: T;
|
||||
height?: T;
|
||||
focalX?: T;
|
||||
focalY?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "payload-kv_select".
|
||||
@@ -439,7 +394,6 @@ export interface SiteSetting {
|
||||
*/
|
||||
export interface Header {
|
||||
id: number;
|
||||
logo?: (number | null) | Media;
|
||||
items?:
|
||||
| {
|
||||
label: string;
|
||||
@@ -467,7 +421,6 @@ export interface SiteSettingsSelect<T extends boolean = true> {
|
||||
* via the `definition` "header_select".
|
||||
*/
|
||||
export interface HeaderSelect<T extends boolean = true> {
|
||||
logo?: T;
|
||||
items?:
|
||||
| T
|
||||
| {
|
||||
|
||||
@@ -5,7 +5,7 @@ describe("payloadConfig composition", () => {
|
||||
it("registers all feature collections", async () => {
|
||||
const resolved = await config;
|
||||
const slugs = resolved.collections?.map((c) => c.slug) ?? [];
|
||||
expect(slugs).toEqual(expect.arrayContaining(["users", "pages", "media"]));
|
||||
expect(slugs).toEqual(expect.arrayContaining(["users", "pages"]));
|
||||
});
|
||||
|
||||
it("registers all feature globals", async () => {
|
||||
|
||||
@@ -5,7 +5,6 @@ import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { users } from "@repo/auth/cms";
|
||||
import { media } from "@repo/media/cms";
|
||||
import { pages, siteSettings } from "@repo/marketing-pages/cms";
|
||||
import { header } from "@repo/navigation/cms";
|
||||
|
||||
@@ -14,7 +13,7 @@ const dirname = path.dirname(filename);
|
||||
|
||||
export default buildConfig({
|
||||
editor: lexicalEditor(),
|
||||
collections: [users, pages, media],
|
||||
collections: [users, pages],
|
||||
globals: [siteSettings, header],
|
||||
secret: process.env.PAYLOAD_SECRET || "default-secret-change-me",
|
||||
db: postgresAdapter({
|
||||
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = join(__dirname, "..", "..");
|
||||
const FEATURES = ["auth", "media", "marketing-pages", "navigation"];
|
||||
const FEATURES = ["auth", "marketing-pages", "navigation"];
|
||||
const ANCHORS = {
|
||||
"src/index.ts": ["// <gen:events>", "// <gen:realtime-channels>"],
|
||||
"src/di/symbols.ts": [
|
||||
|
||||
@@ -45,11 +45,6 @@ export const pages: CollectionConfig = {
|
||||
fields: [
|
||||
{ name: "heading", type: "text", required: true },
|
||||
{ name: "subheading", type: "textarea" },
|
||||
{
|
||||
name: "image",
|
||||
type: "upload",
|
||||
relationTo: "media",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
# AGENTS.md — media
|
||||
|
||||
Media upload collection (images, PDFs, etc.) and media-related use cases (get, list, delete). Provides the Media Payload collection and tRPC procedures for asset management.
|
||||
|
||||
## Overview
|
||||
|
||||
`@repo/media` owns: Media domain model, media-scoped errors, the `IMediaRepository` interface, three use cases, three controllers, a real Payload-backed repository, and the tRPC `mediaRouter`. No query builders today — `./ui` is a placeholder.
|
||||
|
||||
## Layer responsibilities
|
||||
|
||||
| Layer | Key files |
|
||||
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||
| **entities/models** | `media.ts` — `mediaSchema` + `Media` type (filename, mimeType, filesize, url, etc.) |
|
||||
| **entities/errors** | `media.ts` (MediaNotFoundError), `common.ts` (InputParseError) |
|
||||
| **application/use-cases** | `get-media.use-case.ts`, `list-media.use-case.ts`, `delete-media.use-case.ts` — factory functions + exported schemas |
|
||||
| **application/repositories** | `media.repository.interface.ts` — `IMediaRepository` |
|
||||
| **infrastructure/repositories** | `media.repository.ts` (real Payload-backed), `media.repository.mock.ts` (in-memory) |
|
||||
| **interface-adapters/controllers** | `get-media.controller.ts`, `list-media.controller.ts`, `delete-media.controller.ts` — one file per use case |
|
||||
| **di** | `symbols.ts` (MEDIA_SYMBOLS), `module.ts`, `container.ts`, `bind-production.ts` |
|
||||
| **integrations/api** | `procedures.ts` (mediaProcedure), `router.ts` (mediaRouter), `index.ts` |
|
||||
| **integrations/cms** | `collections/media.ts` — Payload Media CollectionConfig |
|
||||
| **ui** | `src/ui/index.ts` — placeholder (no query builders today) |
|
||||
|
||||
### DI symbols
|
||||
|
||||
`MEDIA_SYMBOLS` includes: `IMediaRepository`, `IGetMediaUseCase`, `IListMediaUseCase`, `IDeleteMediaUseCase`, `IGetMediaController`, `IListMediaController`, `IDeleteMediaController`.
|
||||
|
||||
## Public exports
|
||||
|
||||
| Subpath | Contents |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `.` | `Media` type; `MediaNotFoundError`, `InputParseError`; `getMediaInputSchema`, `getMediaOutputSchema`, `listMediaInputSchema`, `listMediaOutputSchema`, `deleteMediaInputSchema`; all `XInput`/`XOutput` types + `IXUseCase` aliases; `IXController` type aliases; `MediaRouter` type |
|
||||
| `./ui` | Placeholder — extend here when media gains React Query builders, never re-add to root |
|
||||
| `./api` | `mediaRouter` (tRPC router) |
|
||||
| `./cms` | Payload Media collection definition |
|
||||
| `./di/bind-production` | `bindProductionMedia(ctx: BindProductionContext)` — swaps mock impls for real Payload-backed ones at app boot |
|
||||
| `./di/bind-dev-seed` | `bindDevSeedMedia(ctx: BindContext)` — replaces the default empty mock with a populated one for dev / Storybook |
|
||||
|
||||
## Use-case + controller patterns
|
||||
|
||||
See `CLAUDE.md` Key Conventions and `docs/architecture/overview.md` for the canonical factory templates.
|
||||
|
||||
### Use cases
|
||||
|
||||
| Use case | Input schema | Output schema | Notes |
|
||||
| -------------------- | ----------------------------------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------- |
|
||||
| `getMediaUseCase` | `getMediaInputSchema` — `{ id: string }` | `getMediaOutputSchema` — `= mediaSchema` | Throws `MediaNotFoundError` when id not found; ends with `getMediaOutputSchema.parse(media)` |
|
||||
| `listMediaUseCase` | `listMediaInputSchema` — `{ limit?: int, offset?: int }` (strict) | `listMediaOutputSchema` — `z.array(mediaSchema)` | Returns paginated list; ends with `listMediaOutputSchema.parse(result)` |
|
||||
| `deleteMediaUseCase` | `deleteMediaInputSchema` — `{ id: string }` | void (no `xOutputSchema`) | Throws `MediaNotFoundError` when id not found; no output schema |
|
||||
|
||||
### Controllers
|
||||
|
||||
| Controller | Presenter | Return type |
|
||||
| ----------------------- | ------------------ | ------------------------------------------------- |
|
||||
| `getMediaController` | identity presenter | `Promise<ReturnType<typeof presenter>>` (Media) |
|
||||
| `listMediaController` | identity presenter | `Promise<ReturnType<typeof presenter>>` (Media[]) |
|
||||
| `deleteMediaController` | none (void) | `Promise<void>` |
|
||||
|
||||
All controllers accept `unknown` input and `safeParse` with the use-case's `xInputSchema`, throwing `InputParseError` on failure.
|
||||
|
||||
## Errors → tRPC codes
|
||||
|
||||
| Error class | tRPC code | Thrown by |
|
||||
| -------------------- | ------------- | --------------------------------------- |
|
||||
| `InputParseError` | `BAD_REQUEST` | controllers (safeParse failure) |
|
||||
| `MediaNotFoundError` | `NOT_FOUND` | `getMediaUseCase`, `deleteMediaUseCase` |
|
||||
|
||||
Defined in `src/integrations/api/procedures.ts` via `mediaProcedure = t.procedure.use(defineErrorMiddleware([...]))`.
|
||||
|
||||
## Tests
|
||||
|
||||
- **Factories:** `src/__factories__/media.factory.ts`
|
||||
- **Contract suite:** `src/__contracts__/media-repository.contract.ts` — runs against mock and real `MediaRepository`
|
||||
- **Unit tests:** colocated `*.test.ts` next to each source file
|
||||
- **Feature integration:** `src/integrations/api/router.test.ts` — R26 router error-mapping tests (covers all three procedures)
|
||||
- **R25** (output validation): `get-media.use-case.test.ts` and `list-media.use-case.test.ts` each have tests that inject a repository mock returning malformed data and assert `.rejects.toBeInstanceOf(ZodError)`. `deleteMedia` is void — no R25.
|
||||
- **R26** (router error mapping): `router.test.ts` asserts `NOT_FOUND` on `getMedia` with nonexistent id, `BAD_REQUEST` on `getMedia` with empty input, `NOT_FOUND` on `deleteMedia` with nonexistent id, and `NOT_FOUND` via an inline `NullMediaRepository` rebind.
|
||||
- **R27/R28** (presenter shape): `getMedia` and `listMedia` use identity presenters — no reshape test obligation. `deleteMedia` is void — no presenter.
|
||||
|
||||
```bash
|
||||
pnpm test --filter @repo/media
|
||||
pnpm test --filter @repo/media -- --watch
|
||||
```
|
||||
|
||||
See `docs/guides/tdd-workflow.md` for the full cycle.
|
||||
|
||||
## Directory structure
|
||||
|
||||
```
|
||||
src/
|
||||
entities/
|
||||
models/
|
||||
media.ts # mediaSchema, Media type
|
||||
errors/
|
||||
media.ts # MediaNotFoundError
|
||||
common.ts # InputParseError
|
||||
application/
|
||||
repositories/
|
||||
media.repository.interface.ts
|
||||
use-cases/
|
||||
get-media.use-case.ts
|
||||
list-media.use-case.ts
|
||||
delete-media.use-case.ts
|
||||
infrastructure/
|
||||
repositories/
|
||||
media.repository.ts # real Payload-backed
|
||||
media.repository.mock.ts
|
||||
interface-adapters/
|
||||
controllers/
|
||||
get-media.controller.ts
|
||||
list-media.controller.ts
|
||||
delete-media.controller.ts
|
||||
integrations/
|
||||
api/
|
||||
procedures.ts # mediaProcedure
|
||||
router.ts # mediaRouter
|
||||
index.ts
|
||||
cms/
|
||||
collections/
|
||||
media.ts
|
||||
index.ts
|
||||
di/
|
||||
symbols.ts # MEDIA_SYMBOLS
|
||||
module.ts
|
||||
container.ts
|
||||
bind-production.ts
|
||||
ui/
|
||||
index.ts # placeholder
|
||||
index.ts
|
||||
__factories__/
|
||||
media.factory.ts
|
||||
__contracts__/
|
||||
media-repository.contract.ts
|
||||
```
|
||||
|
||||
## What it must NOT import
|
||||
|
||||
- Any other feature package (`@repo/auth`, `@repo/blog`, etc.)
|
||||
- Any app package
|
||||
- `@repo/core-api`, `@repo/core-cms`, `@repo/core-trpc`, `@repo/core-ui` directly; only `@repo/core-shared`
|
||||
> Note: `@repo/core-trpc` and `@repo/core-ui` are optional packages scaffolded via `pnpm turbo gen core-package trpc` / `ui`. If not present, these constraints still apply to any future installation.
|
||||
|
||||
## Cross-links
|
||||
|
||||
- ADR-012 (`docs/decisions/adr-012-feature-conventions.md`) — factory-style use cases, per-use-case controllers, file-naming conventions
|
||||
- ADR-013 (`docs/decisions/adr-013-input-output-unification.md`) — schemas-in-use-case, presenter, `./ui` subpath, error middleware
|
||||
@@ -1,11 +0,0 @@
|
||||
# Changelog — @repo/media
|
||||
|
||||
All notable changes to the `media` feature package. Maintained by [release-please](https://github.com/googleapis/release-please) on merges to `main`. See [ADR-021](../../docs/decisions/adr-021-versioning-and-changelog.md) and [`docs/guides/releasing.md`](../../docs/guides/releasing.md).
|
||||
|
||||
## 0.1.0 (2026-05-13)
|
||||
|
||||
### Initial baseline
|
||||
|
||||
The `media` feature established at v0.1.0 alongside the hybrid versioning rollout (ADR-021). The feature has been stable since the template-reset cleanup; this is the first formally versioned baseline.
|
||||
|
||||
Future entries appear above this section as release-please assembles them from conventional commits scoped to `packages/media/**` since the last release.
|
||||
@@ -1,3 +0,0 @@
|
||||
import baseConfig from "@repo/core-eslint/base";
|
||||
|
||||
export default baseConfig;
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"name": "@repo/media",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./ui": "./src/ui/index.ts",
|
||||
"./cms": "./src/integrations/cms/index.ts",
|
||||
"./api": "./src/integrations/api/index.ts",
|
||||
"./di/bind-production": "./src/di/bind-production.ts",
|
||||
"./di/bind-dev-seed": "./src/di/bind-dev-seed.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc --noEmit",
|
||||
"lint": "eslint .",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@repo/core-shared": "workspace:*",
|
||||
"@trpc/server": "^11.0.0",
|
||||
"inversify": "^6.2.0",
|
||||
"payload": "^3.14.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"zod": "^3.24.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@repo/core-eslint": "workspace:*",
|
||||
"@repo/core-testing": "workspace:*",
|
||||
"@repo/core-typescript": "workspace:*",
|
||||
"@types/node": "^22.0.0",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"vitest": "^3.1.0"
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import { it, expect, beforeEach, describe } from "vitest";
|
||||
import { defineContractSuite } from "@repo/core-testing/contract";
|
||||
import type { IMediaRepository } from "../application/repositories/media.repository.interface";
|
||||
import { mediaFactory } from "../__factories__/media.factory";
|
||||
|
||||
export const mediaRepositoryContract = defineContractSuite<IMediaRepository>(
|
||||
"IMediaRepository",
|
||||
({ buildSubject, getTracer }) => {
|
||||
let repo: IMediaRepository;
|
||||
|
||||
beforeEach(async () => {
|
||||
mediaFactory.reset();
|
||||
repo = await buildSubject();
|
||||
});
|
||||
|
||||
// --- getMedia ---
|
||||
|
||||
it("getMedia returns undefined for a missing id", async () => {
|
||||
const result = await repo.getMedia("does-not-exist");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
// --- listMedia ---
|
||||
|
||||
it("listMedia returns empty array when no media exists", async () => {
|
||||
const result = await repo.listMedia();
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
// --- deleteMedia ---
|
||||
|
||||
it("deleteMedia removes the item so getMedia returns undefined", async () => {
|
||||
const seed = mediaFactory.build({ id: "contract-1" });
|
||||
// @ts-expect-error _store is a test helper on MockMediaRepository
|
||||
if (typeof repo._store === "function") {
|
||||
// @ts-expect-error _store is a test helper
|
||||
await repo._store(seed);
|
||||
}
|
||||
await repo.deleteMedia("contract-1");
|
||||
const result = await repo.getMedia("contract-1");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("listMedia with limit returns at most limit items", async () => {
|
||||
// Only verifiable on mock; for real impl this checks the interface
|
||||
const result = await repo.listMedia({ limit: 0 });
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("listMedia with offset skips items", async () => {
|
||||
const result = await repo.listMedia({ offset: 100 });
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("getMedia returns undefined for empty string id", async () => {
|
||||
const result = await repo.getMedia("");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
describe("span emission", () => {
|
||||
it("getMedia emits media.getMedia span with id attribute", async () => {
|
||||
if (!getTracer) return;
|
||||
const tracer = getTracer();
|
||||
tracer.reset();
|
||||
await repo.getMedia("nonexistent");
|
||||
const span = tracer.findSpan("media.getMedia");
|
||||
expect(span).toBeDefined();
|
||||
expect(span!.op).toBe("repository");
|
||||
expect(span!.attributes.id).toBe("nonexistent");
|
||||
});
|
||||
|
||||
it("listMedia emits media.listMedia span with op=repository", async () => {
|
||||
if (!getTracer) return;
|
||||
const tracer = getTracer();
|
||||
tracer.reset();
|
||||
await repo.listMedia({ limit: 10 });
|
||||
const span = tracer.findSpan("media.listMedia");
|
||||
expect(span).toBeDefined();
|
||||
expect(span!.op).toBe("repository");
|
||||
expect(span!.attributes.limit).toBe(10);
|
||||
});
|
||||
|
||||
it("deleteMedia emits media.deleteMedia span with id attribute", async () => {
|
||||
if (!getTracer) return;
|
||||
const tracer = getTracer();
|
||||
tracer.reset();
|
||||
await repo.deleteMedia("nonexistent");
|
||||
const span = tracer.findSpan("media.deleteMedia");
|
||||
expect(span).toBeDefined();
|
||||
expect(span!.op).toBe("repository");
|
||||
expect(span!.attributes.id).toBe("nonexistent");
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,2 +0,0 @@
|
||||
export { mediaFactory } from "./media.factory";
|
||||
export type { Media } from "../entities/models/media";
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { mediaFactory } from "@/__factories__/media.factory";
|
||||
|
||||
describe("mediaFactory", () => {
|
||||
beforeEach(() => mediaFactory.reset());
|
||||
|
||||
it("returns a Media object with stable defaults", () => {
|
||||
const m = mediaFactory.build();
|
||||
expect(m.id).toBe("media-1");
|
||||
expect(m.alt).toBe("Media 1");
|
||||
expect(m.mimeType).toBe("image/png");
|
||||
expect(m.filesize).toBe(1024);
|
||||
});
|
||||
|
||||
it("applies overrides", () => {
|
||||
const m = mediaFactory.build({ alt: "Custom alt", mimeType: "image/jpeg" });
|
||||
expect(m.alt).toBe("Custom alt");
|
||||
expect(m.mimeType).toBe("image/jpeg");
|
||||
expect(m.id).toBe("media-1");
|
||||
});
|
||||
|
||||
it("increments sequence per build", () => {
|
||||
const a = mediaFactory.build();
|
||||
const b = mediaFactory.build();
|
||||
expect(a.id).toBe("media-1");
|
||||
expect(b.id).toBe("media-2");
|
||||
});
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
import { defineFactory } from "@repo/core-testing/factory";
|
||||
import type { Media } from "../entities/models/media";
|
||||
|
||||
export const mediaFactory = defineFactory<Media>(({ sequence }) => ({
|
||||
id: `media-${sequence}`,
|
||||
alt: `Media ${sequence}`,
|
||||
url: `https://cdn.example.com/media-${sequence}.png`,
|
||||
filename: `media-${sequence}.png`,
|
||||
mimeType: "image/png",
|
||||
filesize: 1024,
|
||||
}));
|
||||
@@ -1,38 +0,0 @@
|
||||
import { mediaFactory } from "../__factories__/media.factory";
|
||||
import type { Media } from "../entities/models/media";
|
||||
|
||||
/**
|
||||
* Realistic media seed for dev mode + storybook stories.
|
||||
*
|
||||
* Built from `mediaFactory` so factory defaults take care of boring fields
|
||||
* and we only override what makes the data look like a real media library.
|
||||
*
|
||||
* Lazily produced so importing this module is side-effect-free — the
|
||||
* factory's sequence counter only advances when a binder calls
|
||||
* `buildDevMedia()`.
|
||||
*/
|
||||
export function buildDevMedia(): Media[] {
|
||||
return [
|
||||
mediaFactory.build({
|
||||
id: "placeholder-1",
|
||||
alt: "Hero background image",
|
||||
url: "/dev/placeholder-1.jpg",
|
||||
filename: "placeholder-1.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
}),
|
||||
mediaFactory.build({
|
||||
id: "placeholder-2",
|
||||
alt: "Team photo",
|
||||
url: "/dev/placeholder-2.jpg",
|
||||
filename: "placeholder-2.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
}),
|
||||
mediaFactory.build({
|
||||
id: "placeholder-3",
|
||||
alt: "Product screenshot",
|
||||
url: "/dev/placeholder-3.png",
|
||||
filename: "placeholder-3.png",
|
||||
mimeType: "image/png",
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { Media } from "../../entities/models/media";
|
||||
|
||||
export interface IMediaRepository {
|
||||
getMedia(id: string): Promise<Media | undefined>;
|
||||
listMedia(opts?: { limit?: number; offset?: number }): Promise<Media[]>;
|
||||
deleteMedia(id: string): Promise<void>;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { deleteMediaUseCase } from "@/application/use-cases/delete-media.use-case";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import { MediaNotFoundError } from "@/entities/errors/media";
|
||||
import { mediaFactory } from "@/__factories__/media.factory";
|
||||
|
||||
describe("deleteMediaUseCase", () => {
|
||||
it("deletes media when found", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const seed = mediaFactory.build({ id: "m-1" });
|
||||
await repo._store(seed);
|
||||
|
||||
const useCase = deleteMediaUseCase(repo);
|
||||
await useCase({ id: "m-1" });
|
||||
|
||||
const result = await repo.getMedia("m-1");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("throws MediaNotFoundError when id does not exist", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = deleteMediaUseCase(repo);
|
||||
|
||||
await expect(useCase({ id: "missing" })).rejects.toThrow(MediaNotFoundError);
|
||||
});
|
||||
});
|
||||
@@ -1,23 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { MediaNotFoundError } from "../../entities/errors/media";
|
||||
import type { IMediaRepository } from "../repositories/media.repository.interface";
|
||||
|
||||
// ── Input ────────────────────────────────────────────────────────────────
|
||||
export const deleteMediaInputSchema = z.object({ id: z.string().min(1) }).strict();
|
||||
export type DeleteMediaInput = z.infer<typeof deleteMediaInputSchema>;
|
||||
|
||||
// No output schema — use case returns void.
|
||||
|
||||
// ── Use case ─────────────────────────────────────────────────────────────
|
||||
export type IDeleteMediaUseCase = ReturnType<typeof deleteMediaUseCase>;
|
||||
|
||||
export const deleteMediaUseCase =
|
||||
(mediaRepository: IMediaRepository) =>
|
||||
async (input: DeleteMediaInput): Promise<void> => {
|
||||
const existing = await mediaRepository.getMedia(input.id);
|
||||
if (!existing) {
|
||||
throw new MediaNotFoundError(`Media with id "${input.id}" not found`);
|
||||
}
|
||||
await mediaRepository.deleteMedia(input.id);
|
||||
};
|
||||
@@ -1,46 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ZodError } from "zod";
|
||||
import {
|
||||
getMediaUseCase,
|
||||
getMediaOutputSchema,
|
||||
} from "@/application/use-cases/get-media.use-case";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import { MediaNotFoundError } from "@/entities/errors/media";
|
||||
import { mediaFactory } from "@/__factories__/media.factory";
|
||||
|
||||
describe("getMediaUseCase", () => {
|
||||
it("returns media when found", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const seed = mediaFactory.build({ id: "m-1" });
|
||||
await repo._store(seed);
|
||||
|
||||
const useCase = getMediaUseCase(repo);
|
||||
const result = await useCase({ id: "m-1" });
|
||||
|
||||
expect(result.id).toBe("m-1");
|
||||
expect(result.alt).toBe(seed.alt);
|
||||
});
|
||||
|
||||
it("throws MediaNotFoundError when id does not exist", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = getMediaUseCase(repo);
|
||||
|
||||
await expect(useCase({ id: "missing" })).rejects.toThrow(
|
||||
MediaNotFoundError,
|
||||
);
|
||||
});
|
||||
|
||||
it("parses valid output without error", async () => {
|
||||
const validMedia = mediaFactory.build({ id: "m-r25" });
|
||||
expect(() => getMediaOutputSchema.parse(validMedia)).not.toThrow();
|
||||
});
|
||||
|
||||
it("throws ZodError when repository returns malformed media", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
// Store a malformed object (missing required fields) via type cast
|
||||
await repo._store({ id: "bad", alt: "alt", url: "u" } as never);
|
||||
|
||||
const useCase = getMediaUseCase(repo);
|
||||
await expect(useCase({ id: "bad" })).rejects.toBeInstanceOf(ZodError);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { MediaNotFoundError } from "../../entities/errors/media";
|
||||
import { mediaSchema } from "../../entities/models/media";
|
||||
import type { IMediaRepository } from "../repositories/media.repository.interface";
|
||||
|
||||
// ── Input ────────────────────────────────────────────────────────────────
|
||||
export const getMediaInputSchema = z.object({ id: z.string().min(1) }).strict();
|
||||
export type GetMediaInput = z.infer<typeof getMediaInputSchema>;
|
||||
|
||||
// ── Output ───────────────────────────────────────────────────────────────
|
||||
export const getMediaOutputSchema = mediaSchema;
|
||||
export type GetMediaOutput = z.infer<typeof getMediaOutputSchema>;
|
||||
|
||||
// ── Use case ─────────────────────────────────────────────────────────────
|
||||
export type IGetMediaUseCase = ReturnType<typeof getMediaUseCase>;
|
||||
|
||||
export const getMediaUseCase =
|
||||
(mediaRepository: IMediaRepository) =>
|
||||
async (input: GetMediaInput): Promise<GetMediaOutput> => {
|
||||
const media = await mediaRepository.getMedia(input.id);
|
||||
if (!media) {
|
||||
throw new MediaNotFoundError(`Media with id "${input.id}" not found`);
|
||||
}
|
||||
return getMediaOutputSchema.parse(media);
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ZodError } from "zod";
|
||||
import {
|
||||
listMediaUseCase,
|
||||
listMediaOutputSchema,
|
||||
} from "@/application/use-cases/list-media.use-case";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import { mediaFactory } from "@/__factories__/media.factory";
|
||||
|
||||
describe("listMediaUseCase", () => {
|
||||
it("returns empty array when no media exists", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = listMediaUseCase(repo);
|
||||
const result = await useCase({});
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns all media when store has items", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
await repo._store(mediaFactory.build());
|
||||
await repo._store(mediaFactory.build());
|
||||
|
||||
const useCase = listMediaUseCase(repo);
|
||||
const result = await useCase({});
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("respects limit and offset options", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await repo._store(mediaFactory.build());
|
||||
}
|
||||
|
||||
const useCase = listMediaUseCase(repo);
|
||||
const result = await useCase({ limit: 2, offset: 1 });
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("parses valid output without error", async () => {
|
||||
const items = [mediaFactory.build(), mediaFactory.build()];
|
||||
expect(() => listMediaOutputSchema.parse(items)).not.toThrow();
|
||||
});
|
||||
|
||||
it("throws ZodError when repository returns malformed items", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
// Store a malformed object (missing required fields)
|
||||
await repo._store({ id: "bad", alt: "alt", url: "u" } as never);
|
||||
|
||||
const useCase = listMediaUseCase(repo);
|
||||
await expect(useCase({})).rejects.toBeInstanceOf(ZodError);
|
||||
});
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { mediaSchema } from "../../entities/models/media";
|
||||
import type { IMediaRepository } from "../repositories/media.repository.interface";
|
||||
|
||||
// ── Input ────────────────────────────────────────────────────────────────
|
||||
export const listMediaInputSchema = z
|
||||
.object({
|
||||
limit: z.number().int().positive().optional(),
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
})
|
||||
.strict();
|
||||
export type ListMediaInput = z.infer<typeof listMediaInputSchema>;
|
||||
|
||||
// ── Output ───────────────────────────────────────────────────────────────
|
||||
export const listMediaOutputSchema = z.array(mediaSchema);
|
||||
export type ListMediaOutput = z.infer<typeof listMediaOutputSchema>;
|
||||
|
||||
// ── Use case ─────────────────────────────────────────────────────────────
|
||||
export type IListMediaUseCase = ReturnType<typeof listMediaUseCase>;
|
||||
|
||||
export const listMediaUseCase =
|
||||
(mediaRepository: IMediaRepository) =>
|
||||
async (input: ListMediaInput): Promise<ListMediaOutput> => {
|
||||
const result = await mediaRepository.listMedia(input);
|
||||
return listMediaOutputSchema.parse(result);
|
||||
};
|
||||
@@ -1,75 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { NoopTracer, NoopLogger } from "@repo/core-shared/instrumentation";
|
||||
import { RecordingEventBus, RecordingJobQueue } from "@repo/core-testing/instrumentation";
|
||||
import { bindDevSeedMedia } from "@/di/bind-dev-seed";
|
||||
import { mediaContainer } from "@/di/container";
|
||||
import { MEDIA_SYMBOLS } from "@/di/symbols";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import type { IMediaRepository } from "@/application/repositories/media.repository.interface";
|
||||
|
||||
const noop = { tracer: new NoopTracer(), logger: new NoopLogger() };
|
||||
|
||||
describe("bindDevSeedMedia", () => {
|
||||
// Each test starts from the default empty-mock binding and tears down
|
||||
// afterwards so the global mediaContainer state stays clean for siblings.
|
||||
beforeEach(() => {
|
||||
if (mediaContainer.isBound(MEDIA_SYMBOLS.IMediaRepository)) {
|
||||
mediaContainer.unbind(MEDIA_SYMBOLS.IMediaRepository);
|
||||
}
|
||||
mediaContainer
|
||||
.bind<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository)
|
||||
.to(MockMediaRepository);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (mediaContainer.isBound(MEDIA_SYMBOLS.IMediaRepository)) {
|
||||
mediaContainer.unbind(MEDIA_SYMBOLS.IMediaRepository);
|
||||
}
|
||||
mediaContainer
|
||||
.bind<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository)
|
||||
.to(MockMediaRepository);
|
||||
});
|
||||
|
||||
it("populates the repository with the dev media entries", async () => {
|
||||
await bindDevSeedMedia({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
|
||||
|
||||
const repo = mediaContainer.get<IMediaRepository>(
|
||||
MEDIA_SYMBOLS.IMediaRepository,
|
||||
);
|
||||
const all = await repo.listMedia();
|
||||
|
||||
expect(all.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("seeds placeholder-1 reachable by id", async () => {
|
||||
await bindDevSeedMedia({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
|
||||
|
||||
const repo = mediaContainer.get<IMediaRepository>(
|
||||
MEDIA_SYMBOLS.IMediaRepository,
|
||||
);
|
||||
const item = await repo.getMedia("placeholder-1");
|
||||
|
||||
expect(item).toBeDefined();
|
||||
expect(item?.url).toBe("/dev/placeholder-1.jpg");
|
||||
expect(item?.alt).toBe("Hero background image");
|
||||
});
|
||||
|
||||
it("is idempotent — calling twice rebuilds a fresh populated repo", async () => {
|
||||
await bindDevSeedMedia({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
|
||||
const before = mediaContainer.get<IMediaRepository>(
|
||||
MEDIA_SYMBOLS.IMediaRepository,
|
||||
);
|
||||
const beforeCount = (await before.listMedia()).length;
|
||||
|
||||
await bindDevSeedMedia({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
|
||||
const after = mediaContainer.get<IMediaRepository>(
|
||||
MEDIA_SYMBOLS.IMediaRepository,
|
||||
);
|
||||
const afterCount = (await after.listMedia()).length;
|
||||
|
||||
expect(afterCount).toBe(beforeCount);
|
||||
// It's a fresh instance — not the previous one.
|
||||
expect(after).not.toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -1,168 +0,0 @@
|
||||
import {
|
||||
withSpan,
|
||||
withCapture,
|
||||
INSTRUMENTATION_SYMBOLS,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
import type { BindContext } from "@repo/core-shared/di";
|
||||
import {
|
||||
assertFeatureConformance,
|
||||
wireUseCase,
|
||||
} from "@repo/core-shared/conformance";
|
||||
import { mediaManifest } from "../feature.manifest";
|
||||
import { mediaContainer } from "./container";
|
||||
import { MEDIA_SYMBOLS } from "./symbols";
|
||||
import { MockMediaRepository } from "../infrastructure/repositories/media.repository.mock";
|
||||
import { buildDevMedia } from "../__seeds__/dev";
|
||||
import { getMediaUseCase } from "../application/use-cases/get-media.use-case";
|
||||
import { listMediaUseCase } from "../application/use-cases/list-media.use-case";
|
||||
import { deleteMediaUseCase } from "../application/use-cases/delete-media.use-case";
|
||||
import { getMediaController } from "../interface-adapters/controllers/get-media.controller";
|
||||
import { listMediaController } from "../interface-adapters/controllers/list-media.controller";
|
||||
import { deleteMediaController } from "../interface-adapters/controllers/delete-media.controller";
|
||||
import type { IMediaRepository } from "../application/repositories/media.repository.interface";
|
||||
|
||||
/**
|
||||
* Replace the default empty mock with a populated one for dev mode + storybook.
|
||||
*
|
||||
* Call this from app boot when `USE_DEV_SEED=true`, mutually exclusive with
|
||||
* `bindProductionMedia(config)`. Tests must NOT call this — they construct
|
||||
* `new MockMediaRepository()` directly and seed via factories per-test.
|
||||
*
|
||||
* Idempotent: safe to call multiple times; each call rebuilds a fresh
|
||||
* populated repo and rebinds the symbol.
|
||||
*/
|
||||
export async function bindDevSeedMedia(ctx: BindContext): Promise<void> {
|
||||
const { tracer, logger, bus, queue, realtime, realtimeRegistry } = ctx;
|
||||
|
||||
// Bind shared instrumentation into feature container
|
||||
if (mediaContainer.isBound(INSTRUMENTATION_SYMBOLS.TRACER)) {
|
||||
mediaContainer.unbind(INSTRUMENTATION_SYMBOLS.TRACER);
|
||||
}
|
||||
if (mediaContainer.isBound(INSTRUMENTATION_SYMBOLS.LOGGER)) {
|
||||
mediaContainer.unbind(INSTRUMENTATION_SYMBOLS.LOGGER);
|
||||
}
|
||||
mediaContainer
|
||||
.bind<ITracer>(INSTRUMENTATION_SYMBOLS.TRACER)
|
||||
.toConstantValue(tracer);
|
||||
mediaContainer
|
||||
.bind<ILogger>(INSTRUMENTATION_SYMBOLS.LOGGER)
|
||||
.toConstantValue(logger);
|
||||
|
||||
if (mediaContainer.isBound(MEDIA_SYMBOLS.IMediaRepository)) {
|
||||
mediaContainer.unbind(MEDIA_SYMBOLS.IMediaRepository);
|
||||
}
|
||||
|
||||
const repo = new MockMediaRepository(tracer, logger);
|
||||
for (const media of buildDevMedia()) {
|
||||
await repo._store(media);
|
||||
}
|
||||
|
||||
mediaContainer
|
||||
.bind<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository)
|
||||
.toConstantValue(repo);
|
||||
|
||||
// Use cases
|
||||
const wrappedGetMedia = wireUseCase({
|
||||
container: mediaContainer,
|
||||
symbol: MEDIA_SYMBOLS.IGetMediaUseCase,
|
||||
factory: getMediaUseCase,
|
||||
deps: [repo],
|
||||
feature: "media",
|
||||
layer: "use-case",
|
||||
name: "getMedia",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
const wrappedListMedia = wireUseCase({
|
||||
container: mediaContainer,
|
||||
symbol: MEDIA_SYMBOLS.IListMediaUseCase,
|
||||
factory: listMediaUseCase,
|
||||
deps: [repo],
|
||||
feature: "media",
|
||||
layer: "use-case",
|
||||
name: "listMedia",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
const wrappedDeleteMedia = wireUseCase({
|
||||
container: mediaContainer,
|
||||
symbol: MEDIA_SYMBOLS.IDeleteMediaUseCase,
|
||||
factory: deleteMediaUseCase,
|
||||
deps: [repo],
|
||||
feature: "media",
|
||||
layer: "use-case",
|
||||
name: "deleteMedia",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
|
||||
for (const sym of [
|
||||
MEDIA_SYMBOLS.IGetMediaController,
|
||||
MEDIA_SYMBOLS.IListMediaController,
|
||||
MEDIA_SYMBOLS.IDeleteMediaController,
|
||||
]) {
|
||||
if (mediaContainer.isBound(sym)) mediaContainer.unbind(sym);
|
||||
}
|
||||
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IGetMediaController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "media.getMedia", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{ feature: "media", layer: "controller", name: "media.getMedia" },
|
||||
getMediaController(wrappedGetMedia),
|
||||
),
|
||||
),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IListMediaController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "media.listMedia", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{ feature: "media", layer: "controller", name: "media.listMedia" },
|
||||
listMediaController(wrappedListMedia),
|
||||
),
|
||||
),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IDeleteMediaController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "media.deleteMedia", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{ feature: "media", layer: "controller", name: "media.deleteMedia" },
|
||||
deleteMediaController(wrappedDeleteMedia),
|
||||
),
|
||||
),
|
||||
);
|
||||
// bus + queue are passed through; generated handlers consume them at the anchors below.
|
||||
void bus;
|
||||
void queue;
|
||||
void realtime;
|
||||
void realtimeRegistry;
|
||||
// <gen:event-handlers>
|
||||
// <gen:jobs>
|
||||
// <gen:realtime-handlers>
|
||||
|
||||
// Boot-time conformance check (dev-seed mode).
|
||||
assertFeatureConformance(
|
||||
mediaContainer,
|
||||
mediaManifest,
|
||||
{
|
||||
getMedia: MEDIA_SYMBOLS.IGetMediaUseCase,
|
||||
listMedia: MEDIA_SYMBOLS.IListMediaUseCase,
|
||||
deleteMedia: MEDIA_SYMBOLS.IDeleteMediaUseCase,
|
||||
},
|
||||
ctx,
|
||||
);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { SanitizedConfig } from "payload";
|
||||
import { NoopTracer, NoopLogger } from "@repo/core-shared/instrumentation";
|
||||
import { bindProductionMedia } from "@/di/bind-production";
|
||||
|
||||
describe("bindProductionMedia — boot-time conformance", () => {
|
||||
it("binds every manifest use case through withSpan + withCapture", () => {
|
||||
expect(() =>
|
||||
bindProductionMedia({
|
||||
config: {} as SanitizedConfig,
|
||||
tracer: new NoopTracer(),
|
||||
logger: new NoopLogger(),
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,151 +0,0 @@
|
||||
import {
|
||||
withSpan,
|
||||
withCapture,
|
||||
INSTRUMENTATION_SYMBOLS,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
import type { BindProductionContext } from "@repo/core-shared/di";
|
||||
import {
|
||||
assertFeatureConformance,
|
||||
wireUseCase,
|
||||
} from "@repo/core-shared/conformance";
|
||||
import { mediaContainer } from "./container";
|
||||
import { MEDIA_SYMBOLS } from "./symbols";
|
||||
import { mediaManifest } from "../feature.manifest";
|
||||
import { MediaRepository } from "../infrastructure/repositories/media.repository";
|
||||
import { getMediaUseCase } from "../application/use-cases/get-media.use-case";
|
||||
import { listMediaUseCase } from "../application/use-cases/list-media.use-case";
|
||||
import { deleteMediaUseCase } from "../application/use-cases/delete-media.use-case";
|
||||
import { getMediaController } from "../interface-adapters/controllers/get-media.controller";
|
||||
import { listMediaController } from "../interface-adapters/controllers/list-media.controller";
|
||||
import { deleteMediaController } from "../interface-adapters/controllers/delete-media.controller";
|
||||
|
||||
export function bindProductionMedia(ctx: BindProductionContext): void {
|
||||
const { config, tracer, logger, bus, queue, realtime, realtimeRegistry } =
|
||||
ctx;
|
||||
|
||||
// Bind shared instrumentation into feature container
|
||||
if (mediaContainer.isBound(INSTRUMENTATION_SYMBOLS.TRACER)) {
|
||||
mediaContainer.unbind(INSTRUMENTATION_SYMBOLS.TRACER);
|
||||
}
|
||||
if (mediaContainer.isBound(INSTRUMENTATION_SYMBOLS.LOGGER)) {
|
||||
mediaContainer.unbind(INSTRUMENTATION_SYMBOLS.LOGGER);
|
||||
}
|
||||
mediaContainer
|
||||
.bind<ITracer>(INSTRUMENTATION_SYMBOLS.TRACER)
|
||||
.toConstantValue(tracer);
|
||||
mediaContainer
|
||||
.bind<ILogger>(INSTRUMENTATION_SYMBOLS.LOGGER)
|
||||
.toConstantValue(logger);
|
||||
|
||||
// Real repository
|
||||
if (mediaContainer.isBound(MEDIA_SYMBOLS.IMediaRepository)) {
|
||||
mediaContainer.unbind(MEDIA_SYMBOLS.IMediaRepository);
|
||||
}
|
||||
const repo = new MediaRepository(config, tracer, logger);
|
||||
mediaContainer.bind(MEDIA_SYMBOLS.IMediaRepository).toConstantValue(repo);
|
||||
|
||||
// Use cases
|
||||
const wrappedGetMedia = wireUseCase({
|
||||
container: mediaContainer,
|
||||
symbol: MEDIA_SYMBOLS.IGetMediaUseCase,
|
||||
factory: getMediaUseCase,
|
||||
deps: [repo],
|
||||
feature: "media",
|
||||
layer: "use-case",
|
||||
name: "getMedia",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
const wrappedListMedia = wireUseCase({
|
||||
container: mediaContainer,
|
||||
symbol: MEDIA_SYMBOLS.IListMediaUseCase,
|
||||
factory: listMediaUseCase,
|
||||
deps: [repo],
|
||||
feature: "media",
|
||||
layer: "use-case",
|
||||
name: "listMedia",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
const wrappedDeleteMedia = wireUseCase({
|
||||
container: mediaContainer,
|
||||
symbol: MEDIA_SYMBOLS.IDeleteMediaUseCase,
|
||||
factory: deleteMediaUseCase,
|
||||
deps: [repo],
|
||||
feature: "media",
|
||||
layer: "use-case",
|
||||
name: "deleteMedia",
|
||||
tracer,
|
||||
logger,
|
||||
});
|
||||
|
||||
// Controllers — wrapped with span at bind time
|
||||
for (const sym of [
|
||||
MEDIA_SYMBOLS.IGetMediaController,
|
||||
MEDIA_SYMBOLS.IListMediaController,
|
||||
MEDIA_SYMBOLS.IDeleteMediaController,
|
||||
]) {
|
||||
if (mediaContainer.isBound(sym)) mediaContainer.unbind(sym);
|
||||
}
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IGetMediaController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "media.getMedia", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{ feature: "media", layer: "controller", name: "media.getMedia" },
|
||||
getMediaController(wrappedGetMedia),
|
||||
),
|
||||
),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IListMediaController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "media.listMedia", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{ feature: "media", layer: "controller", name: "media.listMedia" },
|
||||
listMediaController(wrappedListMedia),
|
||||
),
|
||||
),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IDeleteMediaController)
|
||||
.toConstantValue(
|
||||
withSpan(
|
||||
tracer,
|
||||
{ name: "media.deleteMedia", op: "controller" },
|
||||
withCapture(
|
||||
logger,
|
||||
{ feature: "media", layer: "controller", name: "media.deleteMedia" },
|
||||
deleteMediaController(wrappedDeleteMedia),
|
||||
),
|
||||
),
|
||||
);
|
||||
// bus + queue are passed through; generated handlers consume them at the anchors below.
|
||||
void bus;
|
||||
void queue;
|
||||
void realtime;
|
||||
void realtimeRegistry;
|
||||
// <gen:event-handlers>
|
||||
// <gen:jobs>
|
||||
// <gen:realtime-handlers>
|
||||
|
||||
// Boot-time conformance check.
|
||||
assertFeatureConformance(
|
||||
mediaContainer,
|
||||
mediaManifest,
|
||||
{
|
||||
getMedia: MEDIA_SYMBOLS.IGetMediaUseCase,
|
||||
listMedia: MEDIA_SYMBOLS.IListMediaUseCase,
|
||||
deleteMedia: MEDIA_SYMBOLS.IDeleteMediaUseCase,
|
||||
},
|
||||
ctx,
|
||||
);
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { mediaContainer } from "@/di/container";
|
||||
import { MEDIA_SYMBOLS } from "@/di/symbols";
|
||||
import { MediaModule } from "@/di/module";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import type { IMediaRepository } from "@/application/repositories/media.repository.interface";
|
||||
|
||||
describe("mediaContainer", () => {
|
||||
beforeEach(() => {
|
||||
mediaContainer.unbindAll();
|
||||
mediaContainer.load(MediaModule);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mediaContainer.unbindAll();
|
||||
});
|
||||
|
||||
it("resolves IMediaRepository to MockMediaRepository by default binding", () => {
|
||||
const repo = mediaContainer.get<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository);
|
||||
expect(repo).toBeInstanceOf(MockMediaRepository);
|
||||
});
|
||||
|
||||
it("resolves IGetMediaController as a function", () => {
|
||||
const ctrl = mediaContainer.get(MEDIA_SYMBOLS.IGetMediaController);
|
||||
expect(typeof ctrl).toBe("function");
|
||||
});
|
||||
|
||||
it("resolves IListMediaController as a function", () => {
|
||||
const ctrl = mediaContainer.get(MEDIA_SYMBOLS.IListMediaController);
|
||||
expect(typeof ctrl).toBe("function");
|
||||
});
|
||||
|
||||
it("resolves IDeleteMediaController as a function", () => {
|
||||
const ctrl = mediaContainer.get(MEDIA_SYMBOLS.IDeleteMediaController);
|
||||
expect(typeof ctrl).toBe("function");
|
||||
});
|
||||
|
||||
it("resolves IGetMediaUseCase as a function", () => {
|
||||
const uc = mediaContainer.get(MEDIA_SYMBOLS.IGetMediaUseCase);
|
||||
expect(typeof uc).toBe("function");
|
||||
});
|
||||
|
||||
it("resolves IListMediaUseCase as a function", () => {
|
||||
const uc = mediaContainer.get(MEDIA_SYMBOLS.IListMediaUseCase);
|
||||
expect(typeof uc).toBe("function");
|
||||
});
|
||||
|
||||
it("resolves IDeleteMediaUseCase as a function", () => {
|
||||
const uc = mediaContainer.get(MEDIA_SYMBOLS.IDeleteMediaUseCase);
|
||||
expect(typeof uc).toBe("function");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { Container } from "inversify";
|
||||
import { MediaModule } from "./module";
|
||||
|
||||
export const mediaContainer = new Container({ defaultScope: "Singleton" });
|
||||
mediaContainer.load(MediaModule);
|
||||
@@ -1,69 +0,0 @@
|
||||
import { ContainerModule, type interfaces } from "inversify";
|
||||
|
||||
import type { IMediaRepository } from "../application/repositories/media.repository.interface";
|
||||
import { MockMediaRepository } from "../infrastructure/repositories/media.repository.mock";
|
||||
import {
|
||||
getMediaUseCase,
|
||||
type IGetMediaUseCase,
|
||||
} from "../application/use-cases/get-media.use-case";
|
||||
import {
|
||||
listMediaUseCase,
|
||||
type IListMediaUseCase,
|
||||
} from "../application/use-cases/list-media.use-case";
|
||||
import {
|
||||
deleteMediaUseCase,
|
||||
type IDeleteMediaUseCase,
|
||||
} from "../application/use-cases/delete-media.use-case";
|
||||
import {
|
||||
getMediaController,
|
||||
type IGetMediaController,
|
||||
} from "../interface-adapters/controllers/get-media.controller";
|
||||
import {
|
||||
listMediaController,
|
||||
type IListMediaController,
|
||||
} from "../interface-adapters/controllers/list-media.controller";
|
||||
import {
|
||||
deleteMediaController,
|
||||
type IDeleteMediaController,
|
||||
} from "../interface-adapters/controllers/delete-media.controller";
|
||||
import { MEDIA_SYMBOLS } from "./symbols";
|
||||
|
||||
export const MediaModule = new ContainerModule((bind: interfaces.Bind) => {
|
||||
bind<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository).to(MockMediaRepository);
|
||||
|
||||
bind<IGetMediaUseCase>(MEDIA_SYMBOLS.IGetMediaUseCase).toDynamicValue((ctx) =>
|
||||
getMediaUseCase(
|
||||
ctx.container.get<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository),
|
||||
),
|
||||
);
|
||||
|
||||
bind<IListMediaUseCase>(MEDIA_SYMBOLS.IListMediaUseCase).toDynamicValue((ctx) =>
|
||||
listMediaUseCase(
|
||||
ctx.container.get<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository),
|
||||
),
|
||||
);
|
||||
|
||||
bind<IDeleteMediaUseCase>(MEDIA_SYMBOLS.IDeleteMediaUseCase).toDynamicValue((ctx) =>
|
||||
deleteMediaUseCase(
|
||||
ctx.container.get<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository),
|
||||
),
|
||||
);
|
||||
|
||||
bind<IGetMediaController>(MEDIA_SYMBOLS.IGetMediaController).toDynamicValue((ctx) =>
|
||||
getMediaController(
|
||||
ctx.container.get<IGetMediaUseCase>(MEDIA_SYMBOLS.IGetMediaUseCase),
|
||||
),
|
||||
);
|
||||
|
||||
bind<IListMediaController>(MEDIA_SYMBOLS.IListMediaController).toDynamicValue((ctx) =>
|
||||
listMediaController(
|
||||
ctx.container.get<IListMediaUseCase>(MEDIA_SYMBOLS.IListMediaUseCase),
|
||||
),
|
||||
);
|
||||
|
||||
bind<IDeleteMediaController>(MEDIA_SYMBOLS.IDeleteMediaController).toDynamicValue((ctx) =>
|
||||
deleteMediaController(
|
||||
ctx.container.get<IDeleteMediaUseCase>(MEDIA_SYMBOLS.IDeleteMediaUseCase),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
export const MEDIA_SYMBOLS = {
|
||||
IMediaRepository: Symbol.for("media:IMediaRepository"),
|
||||
// Use cases
|
||||
IGetMediaUseCase: Symbol.for("media:IGetMediaUseCase"),
|
||||
IListMediaUseCase: Symbol.for("media:IListMediaUseCase"),
|
||||
IDeleteMediaUseCase: Symbol.for("media:IDeleteMediaUseCase"),
|
||||
// Controllers
|
||||
IGetMediaController: Symbol.for("media:IGetMediaController"),
|
||||
IListMediaController: Symbol.for("media:IListMediaController"),
|
||||
IDeleteMediaController: Symbol.for("media:IDeleteMediaController"),
|
||||
// <gen:event-handler-symbols>
|
||||
// <gen:job-symbols>
|
||||
// <gen:realtime-handler-symbols>
|
||||
} as const;
|
||||
@@ -1,6 +0,0 @@
|
||||
export class InputParseError extends Error {
|
||||
constructor(message: string, options?: ErrorOptions) {
|
||||
super(message, options);
|
||||
this.name = "InputParseError";
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { MediaNotFoundError } from "@/entities/errors/media";
|
||||
|
||||
describe("MediaNotFoundError", () => {
|
||||
it("is an instance of Error", () => {
|
||||
const err = new MediaNotFoundError();
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err).toBeInstanceOf(MediaNotFoundError);
|
||||
});
|
||||
|
||||
it("has default message", () => {
|
||||
const err = new MediaNotFoundError();
|
||||
expect(err.message).toBe("Media not found");
|
||||
});
|
||||
|
||||
it("accepts a custom message", () => {
|
||||
const err = new MediaNotFoundError("Custom message");
|
||||
expect(err.message).toBe("Custom message");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
export class MediaNotFoundError extends Error {
|
||||
constructor(message = "Media not found", options?: ErrorOptions) {
|
||||
super(message, options);
|
||||
this.name = "MediaNotFoundError";
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mediaSchema } from "@/entities/models/media";
|
||||
|
||||
describe("mediaSchema", () => {
|
||||
it("parses a valid media object", () => {
|
||||
const result = mediaSchema.parse({
|
||||
id: "1",
|
||||
alt: "A photo",
|
||||
url: "https://cdn.example.com/photo.png",
|
||||
filename: "photo.png",
|
||||
mimeType: "image/png",
|
||||
filesize: 1024,
|
||||
});
|
||||
expect(result.id).toBe("1");
|
||||
expect(result.alt).toBe("A photo");
|
||||
});
|
||||
|
||||
it("parses a media object with optional width and height", () => {
|
||||
const result = mediaSchema.parse({
|
||||
id: "2",
|
||||
alt: "A photo",
|
||||
url: "https://cdn.example.com/photo.png",
|
||||
filename: "photo.png",
|
||||
mimeType: "image/png",
|
||||
filesize: 2048,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
});
|
||||
expect(result.width).toBe(1920);
|
||||
expect(result.height).toBe(1080);
|
||||
});
|
||||
|
||||
it("parses without width and height (optional)", () => {
|
||||
const result = mediaSchema.parse({
|
||||
id: "3",
|
||||
alt: "Doc",
|
||||
url: "https://cdn.example.com/doc.pdf",
|
||||
filename: "doc.pdf",
|
||||
mimeType: "application/pdf",
|
||||
filesize: 512,
|
||||
});
|
||||
expect(result.width).toBeUndefined();
|
||||
expect(result.height).toBeUndefined();
|
||||
});
|
||||
|
||||
it("throws for missing required fields", () => {
|
||||
expect(() =>
|
||||
mediaSchema.parse({ id: "1", alt: "x", url: "x" }),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const mediaSchema = z.object({
|
||||
id: z.string(),
|
||||
alt: z.string(),
|
||||
url: z.string(),
|
||||
filename: z.string(),
|
||||
mimeType: z.string(),
|
||||
filesize: z.number(),
|
||||
width: z.number().optional(),
|
||||
height: z.number().optional(),
|
||||
});
|
||||
|
||||
export type Media = z.infer<typeof mediaSchema>;
|
||||
@@ -1,37 +0,0 @@
|
||||
import { defineFeature } from "@repo/core-shared/conformance";
|
||||
|
||||
/**
|
||||
* The media feature's conformance manifest.
|
||||
*/
|
||||
export const mediaManifest = defineFeature({
|
||||
name: "media",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
getMedia: { mutates: false, audits: [], publishes: [], consumes: [] },
|
||||
listMedia: { mutates: false, audits: [], publishes: [], consumes: [] },
|
||||
deleteMedia: { mutates: true, audits: [], publishes: [], consumes: [] },
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
coverage: {
|
||||
bands: {
|
||||
baseline: { statements: 80, branches: 75, functions: 80, lines: 80 },
|
||||
entities: { statements: 100, branches: 100, functions: 100, lines: 100 },
|
||||
"use-cases": {
|
||||
statements: 100,
|
||||
branches: 95,
|
||||
functions: 100,
|
||||
lines: 100,
|
||||
},
|
||||
controllers: {
|
||||
statements: 100,
|
||||
branches: 95,
|
||||
functions: 100,
|
||||
lines: 100,
|
||||
},
|
||||
},
|
||||
mutationTargets: ["entities", "use-cases"],
|
||||
},
|
||||
} as const);
|
||||
|
||||
export type MediaManifest = typeof mediaManifest;
|
||||
@@ -1,34 +0,0 @@
|
||||
export type { Media } from "./entities/models/media";
|
||||
export { MediaNotFoundError } from "./entities/errors/media";
|
||||
export { InputParseError } from "./entities/errors/common";
|
||||
export type { MediaRouter } from "./integrations/api/router";
|
||||
|
||||
// Use case schemas + types
|
||||
export {
|
||||
getMediaInputSchema,
|
||||
getMediaOutputSchema,
|
||||
type GetMediaInput,
|
||||
type GetMediaOutput,
|
||||
type IGetMediaUseCase,
|
||||
} from "./application/use-cases/get-media.use-case";
|
||||
export {
|
||||
listMediaInputSchema,
|
||||
listMediaOutputSchema,
|
||||
type ListMediaInput,
|
||||
type ListMediaOutput,
|
||||
type IListMediaUseCase,
|
||||
} from "./application/use-cases/list-media.use-case";
|
||||
export {
|
||||
deleteMediaInputSchema,
|
||||
type DeleteMediaInput,
|
||||
type IDeleteMediaUseCase,
|
||||
} from "./application/use-cases/delete-media.use-case";
|
||||
|
||||
// Controller type aliases
|
||||
export type { IGetMediaController } from "./interface-adapters/controllers/get-media.controller";
|
||||
export type { IListMediaController } from "./interface-adapters/controllers/list-media.controller";
|
||||
export type { IDeleteMediaController } from "./interface-adapters/controllers/delete-media.controller";
|
||||
|
||||
// <gen:events>
|
||||
// <gen:realtime-channels>
|
||||
export { mediaManifest, type MediaManifest } from "./feature.manifest";
|
||||
@@ -1,12 +0,0 @@
|
||||
import { describe } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import { mediaRepositoryContract } from "@/__contracts__/media-repository.contract";
|
||||
|
||||
describe("MockMediaRepository", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
mediaRepositoryContract.run(
|
||||
() => new MockMediaRepository(tracer),
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
@@ -1,74 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { IMediaRepository } from "../../application/repositories/media.repository.interface";
|
||||
import type { Media } from "../../entities/models/media";
|
||||
|
||||
@injectable()
|
||||
export class MockMediaRepository implements IMediaRepository {
|
||||
private _media: Media[] = [];
|
||||
private tracer: ITracer;
|
||||
private logger: ILogger;
|
||||
|
||||
constructor(
|
||||
tracer: ITracer = new NoopTracer(),
|
||||
logger: ILogger = new NoopLogger(),
|
||||
) {
|
||||
this.tracer = tracer;
|
||||
this.logger = logger;
|
||||
void this.logger; // currently unused; reserved for future mock-thrown captures
|
||||
}
|
||||
|
||||
/** Test helper — seeds the in-memory store directly. */
|
||||
async _store(media: Media): Promise<void> {
|
||||
this._media.push(media);
|
||||
}
|
||||
|
||||
async getMedia(id: string): Promise<Media | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "media.getMedia", op: "repository", attributes: { id } },
|
||||
async (span) => {
|
||||
const found = this._media.find((m) => m.id === id);
|
||||
span.setAttribute("found", Boolean(found));
|
||||
return found;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async listMedia(opts?: { limit?: number; offset?: number }): Promise<Media[]> {
|
||||
return this.tracer.startSpan(
|
||||
{
|
||||
name: "media.listMedia",
|
||||
op: "repository",
|
||||
attributes: {
|
||||
limit: opts?.limit ?? null,
|
||||
offset: opts?.offset ?? null,
|
||||
},
|
||||
},
|
||||
async (span) => {
|
||||
const offset = opts?.offset ?? 0;
|
||||
const limit = opts?.limit ?? 50;
|
||||
const result = this._media.slice(offset, offset + limit);
|
||||
span.setAttribute("count", result.length);
|
||||
return result;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async deleteMedia(id: string): Promise<void> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "media.deleteMedia", op: "repository", attributes: { id } },
|
||||
async (span) => {
|
||||
const before = this._media.length;
|
||||
this._media = this._media.filter((m) => m.id !== id);
|
||||
span.setAttribute("deleted", this._media.length < before);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
RecordingTracer,
|
||||
RecordingLogger,
|
||||
} from "@repo/core-testing/instrumentation";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import type { Media } from "@/entities/models/media";
|
||||
|
||||
const SAMPLE_MEDIA: Media = {
|
||||
id: "m1",
|
||||
alt: "Test image",
|
||||
url: "/test/image.jpg",
|
||||
filename: "image.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
filesize: 1024,
|
||||
};
|
||||
|
||||
// Mock repo also wraps in spans.
|
||||
describe("MockMediaRepository emits spans", () => {
|
||||
it("getMedia emits one span with op='repository' and found attribute", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const logger = new RecordingLogger();
|
||||
const repo = new MockMediaRepository(tracer, logger);
|
||||
await repo._store(SAMPLE_MEDIA);
|
||||
await repo.getMedia("m1");
|
||||
expect(tracer.spans).toHaveLength(1);
|
||||
const getSpan = tracer.findSpan("media.getMedia");
|
||||
expect(getSpan).toBeDefined();
|
||||
expect(getSpan).toMatchObject({ name: "media.getMedia", op: "repository" });
|
||||
expect(getSpan!.attributes.found).toBe(true);
|
||||
});
|
||||
|
||||
it("listMedia emits a span with count attribute", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const repo = new MockMediaRepository(tracer);
|
||||
await repo._store(SAMPLE_MEDIA);
|
||||
tracer.reset();
|
||||
await repo.listMedia({ limit: 10 });
|
||||
expect(tracer.findSpan("media.listMedia")).toBeDefined();
|
||||
expect(tracer.findSpan("media.listMedia")!.attributes.limit).toBe(10);
|
||||
expect(tracer.findSpan("media.listMedia")!.attributes.count).toBe(1);
|
||||
});
|
||||
|
||||
it("deleteMedia emits a span with deleted=true", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const repo = new MockMediaRepository(tracer);
|
||||
await repo._store(SAMPLE_MEDIA);
|
||||
tracer.reset();
|
||||
await repo.deleteMedia("m1");
|
||||
expect(tracer.findSpan("media.deleteMedia")).toBeDefined();
|
||||
expect(tracer.findSpan("media.deleteMedia")!.attributes.deleted).toBe(true);
|
||||
expect(tracer.findSpan("media.deleteMedia")!.attributes.id).toBe("m1");
|
||||
});
|
||||
});
|
||||
@@ -1,140 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { MediaRepository } from "@/infrastructure/repositories/media.repository";
|
||||
import { mediaRepositoryContract } from "@/__contracts__/media-repository.contract";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory Payload stub
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildPayloadStub() {
|
||||
const store = new Map<string, Record<string, unknown>>();
|
||||
|
||||
return {
|
||||
find: vi.fn(
|
||||
async ({
|
||||
limit,
|
||||
page,
|
||||
}: {
|
||||
collection: string;
|
||||
limit?: number;
|
||||
page?: number;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
let docs = Array.from(store.values());
|
||||
const lim = limit ?? 50;
|
||||
const pg = page ?? 1;
|
||||
const offset = (pg - 1) * lim;
|
||||
docs = docs.slice(offset, offset + lim);
|
||||
return { docs };
|
||||
},
|
||||
),
|
||||
findByID: vi.fn(
|
||||
async ({ id }: { collection: string; id: string; overrideAccess?: boolean }) => {
|
||||
const doc = store.get(String(id));
|
||||
if (!doc) {
|
||||
const err = Object.assign(new Error(`Not found: ${id}`), { status: 404 });
|
||||
throw err;
|
||||
}
|
||||
return doc;
|
||||
},
|
||||
),
|
||||
delete: vi.fn(
|
||||
async ({ id }: { collection: string; id: string; overrideAccess?: boolean }) => {
|
||||
store.delete(String(id));
|
||||
return { id };
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("payload", () => ({
|
||||
getPayload: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Contract suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("MediaRepository", () => {
|
||||
describe("contract", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
mediaRepositoryContract.run(
|
||||
async () => {
|
||||
const stub = buildPayloadStub();
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue(stub);
|
||||
return new MediaRepository(stubPayloadConfig, tracer);
|
||||
},
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Impl-specific tests: Payload doc → domain mapping
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
describe("getMedia", () => {
|
||||
it("returns undefined when Payload throws (not found)", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
findByID: vi.fn().mockRejectedValue(
|
||||
Object.assign(new Error("Not found"), { status: 404 }),
|
||||
),
|
||||
});
|
||||
|
||||
const repo = new MediaRepository(stubPayloadConfig);
|
||||
const result = await repo.getMedia("missing-id");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("maps Payload doc fields to domain Media", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
findByID: vi.fn().mockResolvedValue({
|
||||
id: "p-1",
|
||||
alt: "Test image",
|
||||
url: "https://cdn.example.com/test.png",
|
||||
filename: "test.png",
|
||||
mimeType: "image/png",
|
||||
filesize: 2048,
|
||||
width: 800,
|
||||
height: 600,
|
||||
}),
|
||||
});
|
||||
|
||||
const repo = new MediaRepository(stubPayloadConfig);
|
||||
const result = await repo.getMedia("p-1");
|
||||
expect(result?.id).toBe("p-1");
|
||||
expect(result?.alt).toBe("Test image");
|
||||
expect(result?.width).toBe(800);
|
||||
expect(result?.height).toBe(600);
|
||||
});
|
||||
});
|
||||
|
||||
describe("listMedia", () => {
|
||||
it("returns an array of mapped Media docs", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
find: vi.fn().mockResolvedValue({
|
||||
docs: [
|
||||
{
|
||||
id: "m-1",
|
||||
alt: "First",
|
||||
url: "https://cdn.example.com/first.png",
|
||||
filename: "first.png",
|
||||
mimeType: "image/png",
|
||||
filesize: 100,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const repo = new MediaRepository(stubPayloadConfig);
|
||||
const result = await repo.listMedia();
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.id).toBe("m-1");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,149 +0,0 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import { getPayload } from "payload";
|
||||
import type { SanitizedConfig } from "payload";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { IMediaRepository } from "../../application/repositories/media.repository.interface";
|
||||
import type { Media } from "../../entities/models/media";
|
||||
|
||||
type PayloadMediaDoc = {
|
||||
id: string | number;
|
||||
alt?: string | null;
|
||||
url?: string | null;
|
||||
filename?: string | null;
|
||||
mimeType?: string | null;
|
||||
filesize?: number | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
};
|
||||
|
||||
function mapDoc(doc: PayloadMediaDoc): Media {
|
||||
return {
|
||||
id: String(doc.id),
|
||||
alt: doc.alt ?? "",
|
||||
url: doc.url ?? "",
|
||||
filename: doc.filename ?? "",
|
||||
mimeType: doc.mimeType ?? "",
|
||||
filesize: doc.filesize ?? 0,
|
||||
...(doc.width != null && { width: doc.width }),
|
||||
...(doc.height != null && { height: doc.height }),
|
||||
};
|
||||
}
|
||||
|
||||
const FEATURE = "media" as const;
|
||||
const REPO = "media" as const;
|
||||
|
||||
@injectable()
|
||||
export class MediaRepository implements IMediaRepository {
|
||||
private config: SanitizedConfig;
|
||||
private tracer: ITracer;
|
||||
private logger: ILogger;
|
||||
|
||||
constructor(
|
||||
config: SanitizedConfig,
|
||||
tracer: ITracer = new NoopTracer(),
|
||||
logger: ILogger = new NoopLogger(),
|
||||
) {
|
||||
this.config = config;
|
||||
this.tracer = tracer;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
async getMedia(id: string): Promise<Media | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "media.getMedia", op: "repository", attributes: { id } },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const doc = await payload.findByID({
|
||||
collection: "media",
|
||||
id,
|
||||
overrideAccess: true,
|
||||
});
|
||||
span.setAttribute("found", true);
|
||||
return mapDoc(doc as PayloadMediaDoc);
|
||||
} catch (err) {
|
||||
if (
|
||||
err &&
|
||||
typeof err === "object" &&
|
||||
"status" in err &&
|
||||
(err as { status: unknown }).status === 404
|
||||
) {
|
||||
span.setAttribute("found", false);
|
||||
return undefined;
|
||||
}
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getMedia" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async listMedia(opts?: { limit?: number; offset?: number }): Promise<Media[]> {
|
||||
return this.tracer.startSpan(
|
||||
{
|
||||
name: "media.listMedia",
|
||||
op: "repository",
|
||||
attributes: {
|
||||
limit: opts?.limit ?? null,
|
||||
offset: opts?.offset ?? null,
|
||||
},
|
||||
},
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const result = await payload.find({
|
||||
collection: "media",
|
||||
limit: opts?.limit ?? 50,
|
||||
page: opts?.offset
|
||||
? Math.floor(opts.offset / (opts.limit ?? 50)) + 1
|
||||
: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const items = result.docs.map((d) => mapDoc(d as PayloadMediaDoc));
|
||||
span.setAttribute("count", items.length);
|
||||
return items;
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "listMedia" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async deleteMedia(id: string): Promise<void> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "media.deleteMedia", op: "repository", attributes: { id } },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
await payload.delete({
|
||||
collection: "media",
|
||||
id,
|
||||
overrideAccess: true,
|
||||
});
|
||||
span.setAttribute("deleted", true);
|
||||
} catch (err) {
|
||||
span.setAttribute("deleted", false);
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "deleteMedia" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
export { mediaRouter } from "./router";
|
||||
export type { MediaRouter } from "./router";
|
||||
@@ -1,12 +0,0 @@
|
||||
import { t } from "@repo/core-shared/trpc/init";
|
||||
import { defineErrorMiddleware } from "@repo/core-shared/trpc/define-error-middleware";
|
||||
|
||||
import { MediaNotFoundError } from "../../entities/errors/media";
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
|
||||
export const mediaProcedure = t.procedure.use(
|
||||
defineErrorMiddleware([
|
||||
[InputParseError, "BAD_REQUEST"],
|
||||
[MediaNotFoundError, "NOT_FOUND"],
|
||||
]),
|
||||
);
|
||||
@@ -1,140 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { injectable } from "inversify";
|
||||
import { mediaContainer } from "@/di/container";
|
||||
import { MediaModule } from "@/di/module";
|
||||
import { MEDIA_SYMBOLS } from "@/di/symbols";
|
||||
import { getMediaUseCase } from "@/application/use-cases/get-media.use-case";
|
||||
import { listMediaUseCase } from "@/application/use-cases/list-media.use-case";
|
||||
import { deleteMediaUseCase } from "@/application/use-cases/delete-media.use-case";
|
||||
import { getMediaController } from "@/interface-adapters/controllers/get-media.controller";
|
||||
import { listMediaController } from "@/interface-adapters/controllers/list-media.controller";
|
||||
import { deleteMediaController } from "@/interface-adapters/controllers/delete-media.controller";
|
||||
import { mediaRouter } from "@/integrations/api/router";
|
||||
|
||||
describe("mediaRouter", () => {
|
||||
beforeEach(() => {
|
||||
mediaContainer.unbindAll();
|
||||
mediaContainer.load(MediaModule);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mediaContainer.unbindAll();
|
||||
});
|
||||
|
||||
it("exposes getMedia, listMedia, deleteMedia procedures", () => {
|
||||
const names = Object.keys(mediaRouter._def.procedures);
|
||||
expect(names).toContain("getMedia");
|
||||
expect(names).toContain("listMedia");
|
||||
expect(names).toContain("deleteMedia");
|
||||
});
|
||||
|
||||
it("listMedia returns empty array by default", async () => {
|
||||
const caller = mediaRouter.createCaller({});
|
||||
const result = await caller.listMedia({});
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mediaRouter error mapping", () => {
|
||||
beforeEach(() => {
|
||||
mediaContainer.unbindAll();
|
||||
mediaContainer.load(MediaModule);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mediaContainer.unbindAll();
|
||||
});
|
||||
|
||||
it("translates MediaNotFoundError → NOT_FOUND when id is missing", async () => {
|
||||
const caller = mediaRouter.createCaller({});
|
||||
try {
|
||||
await caller.getMedia({ id: "nonexistent-id" });
|
||||
throw new Error("expected throw");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(TRPCError);
|
||||
expect((e as TRPCError).code).toBe("NOT_FOUND");
|
||||
}
|
||||
});
|
||||
|
||||
it("translates zod parse failure → BAD_REQUEST on getMedia with empty id", async () => {
|
||||
const caller = mediaRouter.createCaller({});
|
||||
try {
|
||||
await caller.getMedia({} as unknown as { id: string });
|
||||
throw new Error("expected throw");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(TRPCError);
|
||||
expect((e as TRPCError).code).toBe("BAD_REQUEST");
|
||||
}
|
||||
});
|
||||
|
||||
it("translates MediaNotFoundError → NOT_FOUND on deleteMedia with missing id", async () => {
|
||||
const caller = mediaRouter.createCaller({});
|
||||
try {
|
||||
await caller.deleteMedia({ id: "nonexistent-id" });
|
||||
throw new Error("expected throw");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(TRPCError);
|
||||
expect((e as TRPCError).code).toBe("NOT_FOUND");
|
||||
}
|
||||
});
|
||||
|
||||
it("translates MediaNotFoundError → NOT_FOUND via NullMediaRepository", async () => {
|
||||
@injectable()
|
||||
class NullMediaRepository {
|
||||
async getMedia() {
|
||||
return undefined as never;
|
||||
}
|
||||
async listMedia() {
|
||||
return [] as never;
|
||||
}
|
||||
async deleteMedia() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
mediaContainer.unbindAll();
|
||||
mediaContainer.bind(MEDIA_SYMBOLS.IMediaRepository).to(NullMediaRepository);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IGetMediaUseCase)
|
||||
.toDynamicValue((ctx) =>
|
||||
getMediaUseCase(ctx.container.get(MEDIA_SYMBOLS.IMediaRepository)),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IListMediaUseCase)
|
||||
.toDynamicValue((ctx) =>
|
||||
listMediaUseCase(ctx.container.get(MEDIA_SYMBOLS.IMediaRepository)),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IDeleteMediaUseCase)
|
||||
.toDynamicValue((ctx) =>
|
||||
deleteMediaUseCase(ctx.container.get(MEDIA_SYMBOLS.IMediaRepository)),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IGetMediaController)
|
||||
.toDynamicValue((ctx) =>
|
||||
getMediaController(ctx.container.get(MEDIA_SYMBOLS.IGetMediaUseCase)),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IListMediaController)
|
||||
.toDynamicValue((ctx) =>
|
||||
listMediaController(ctx.container.get(MEDIA_SYMBOLS.IListMediaUseCase)),
|
||||
);
|
||||
mediaContainer
|
||||
.bind(MEDIA_SYMBOLS.IDeleteMediaController)
|
||||
.toDynamicValue((ctx) =>
|
||||
deleteMediaController(
|
||||
ctx.container.get(MEDIA_SYMBOLS.IDeleteMediaUseCase),
|
||||
),
|
||||
);
|
||||
|
||||
const caller = mediaRouter.createCaller({});
|
||||
try {
|
||||
await caller.getMedia({ id: "any-id" });
|
||||
throw new Error("expected throw");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(TRPCError);
|
||||
expect((e as TRPCError).code).toBe("NOT_FOUND");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,31 +0,0 @@
|
||||
import { router } from "@repo/core-shared/trpc/init";
|
||||
|
||||
import { mediaContainer } from "../../di/container";
|
||||
import { MEDIA_SYMBOLS } from "../../di/symbols";
|
||||
|
||||
import { getMediaInputSchema } from "../../application/use-cases/get-media.use-case";
|
||||
import { listMediaInputSchema } from "../../application/use-cases/list-media.use-case";
|
||||
import { deleteMediaInputSchema } from "../../application/use-cases/delete-media.use-case";
|
||||
|
||||
import type { IGetMediaController } from "../../interface-adapters/controllers/get-media.controller";
|
||||
import type { IListMediaController } from "../../interface-adapters/controllers/list-media.controller";
|
||||
import type { IDeleteMediaController } from "../../interface-adapters/controllers/delete-media.controller";
|
||||
|
||||
import { mediaProcedure } from "./procedures";
|
||||
|
||||
export const mediaRouter = router({
|
||||
getMedia: mediaProcedure.input(getMediaInputSchema).query(({ input }) => {
|
||||
const ctrl = mediaContainer.get<IGetMediaController>(MEDIA_SYMBOLS.IGetMediaController);
|
||||
return ctrl(input);
|
||||
}),
|
||||
listMedia: mediaProcedure.input(listMediaInputSchema).query(({ input }) => {
|
||||
const ctrl = mediaContainer.get<IListMediaController>(MEDIA_SYMBOLS.IListMediaController);
|
||||
return ctrl(input);
|
||||
}),
|
||||
deleteMedia: mediaProcedure.input(deleteMediaInputSchema).mutation(({ input }) => {
|
||||
const ctrl = mediaContainer.get<IDeleteMediaController>(MEDIA_SYMBOLS.IDeleteMediaController);
|
||||
return ctrl(input);
|
||||
}),
|
||||
});
|
||||
|
||||
export type MediaRouter = typeof mediaRouter;
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { CollectionConfig } from "payload";
|
||||
|
||||
export const media: CollectionConfig = {
|
||||
slug: "media",
|
||||
custom: {
|
||||
retention: {
|
||||
purgeSchedule: "monthly",
|
||||
postDeletion: {
|
||||
duration: "P90D",
|
||||
trigger: "after-deletion",
|
||||
action: "hard-delete",
|
||||
},
|
||||
},
|
||||
},
|
||||
upload: {
|
||||
mimeTypes: ["image/*", "application/pdf"],
|
||||
},
|
||||
admin: {
|
||||
useAsTitle: "filename",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "alt",
|
||||
type: "text",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -1,2 +0,0 @@
|
||||
export { media } from "./collections/media";
|
||||
// <gen:job-tasks>
|
||||
@@ -1,38 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { deleteMediaController } from "@/interface-adapters/controllers/delete-media.controller";
|
||||
import { deleteMediaUseCase } from "@/application/use-cases/delete-media.use-case";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import { MediaNotFoundError } from "@/entities/errors/media";
|
||||
import { InputParseError } from "@/entities/errors/common";
|
||||
import { mediaFactory } from "@/__factories__/media.factory";
|
||||
|
||||
describe("deleteMediaController", () => {
|
||||
it("deletes media successfully", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const seed = mediaFactory.build({ id: "m-1" });
|
||||
await repo._store(seed);
|
||||
|
||||
const useCase = deleteMediaUseCase(repo);
|
||||
const controller = deleteMediaController(useCase);
|
||||
|
||||
await expect(controller({ id: "m-1" })).resolves.toBeUndefined();
|
||||
const result = await repo.getMedia("m-1");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("throws InputParseError when id is missing", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = deleteMediaUseCase(repo);
|
||||
const controller = deleteMediaController(useCase);
|
||||
|
||||
await expect(controller({})).rejects.toThrow(InputParseError);
|
||||
});
|
||||
|
||||
it("throws MediaNotFoundError when media does not exist", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = deleteMediaUseCase(repo);
|
||||
const controller = deleteMediaController(useCase);
|
||||
|
||||
await expect(controller({ id: "missing" })).rejects.toThrow(MediaNotFoundError);
|
||||
});
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
import {
|
||||
deleteMediaInputSchema,
|
||||
type IDeleteMediaUseCase,
|
||||
} from "../../application/use-cases/delete-media.use-case";
|
||||
|
||||
export type IDeleteMediaController = ReturnType<typeof deleteMediaController>;
|
||||
|
||||
export const deleteMediaController =
|
||||
(deleteMediaUseCase: IDeleteMediaUseCase) =>
|
||||
async (input: unknown): Promise<void> => {
|
||||
const parsed = deleteMediaInputSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new InputParseError("Invalid delete-media input", { cause: parsed.error });
|
||||
}
|
||||
await deleteMediaUseCase(parsed.data);
|
||||
};
|
||||
@@ -1,45 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { getMediaController } from "@/interface-adapters/controllers/get-media.controller";
|
||||
import { getMediaUseCase } from "@/application/use-cases/get-media.use-case";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import { MediaNotFoundError } from "@/entities/errors/media";
|
||||
import { InputParseError } from "@/entities/errors/common";
|
||||
import { mediaFactory } from "@/__factories__/media.factory";
|
||||
|
||||
describe("getMediaController", () => {
|
||||
it("returns media on valid input", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const seed = mediaFactory.build({ id: "m-1" });
|
||||
await repo._store(seed);
|
||||
|
||||
const useCase = getMediaUseCase(repo);
|
||||
const controller = getMediaController(useCase);
|
||||
|
||||
const result = await controller({ id: "m-1" });
|
||||
expect(result.id).toBe("m-1");
|
||||
});
|
||||
|
||||
it("throws InputParseError when id is missing", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = getMediaUseCase(repo);
|
||||
const controller = getMediaController(useCase);
|
||||
|
||||
await expect(controller({})).rejects.toThrow(InputParseError);
|
||||
});
|
||||
|
||||
it("throws InputParseError when id is empty string", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = getMediaUseCase(repo);
|
||||
const controller = getMediaController(useCase);
|
||||
|
||||
await expect(controller({ id: "" })).rejects.toThrow(InputParseError);
|
||||
});
|
||||
|
||||
it("throws MediaNotFoundError when media does not exist", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = getMediaUseCase(repo);
|
||||
const controller = getMediaController(useCase);
|
||||
|
||||
await expect(controller({ id: "missing" })).rejects.toThrow(MediaNotFoundError);
|
||||
});
|
||||
});
|
||||
@@ -1,23 +0,0 @@
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
import {
|
||||
getMediaInputSchema,
|
||||
type GetMediaOutput,
|
||||
type IGetMediaUseCase,
|
||||
} from "../../application/use-cases/get-media.use-case";
|
||||
|
||||
function presenter(value: GetMediaOutput) {
|
||||
return value;
|
||||
}
|
||||
|
||||
export type IGetMediaController = ReturnType<typeof getMediaController>;
|
||||
|
||||
export const getMediaController =
|
||||
(getMediaUseCase: IGetMediaUseCase) =>
|
||||
async (input: unknown): Promise<ReturnType<typeof presenter>> => {
|
||||
const parsed = getMediaInputSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new InputParseError("Invalid get-media input", { cause: parsed.error });
|
||||
}
|
||||
const result = await getMediaUseCase(parsed.data);
|
||||
return presenter(result);
|
||||
};
|
||||
@@ -1,60 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { listMediaController } from "@/interface-adapters/controllers/list-media.controller";
|
||||
import { listMediaUseCase } from "@/application/use-cases/list-media.use-case";
|
||||
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
|
||||
import { InputParseError } from "@/entities/errors/common";
|
||||
import { mediaFactory } from "@/__factories__/media.factory";
|
||||
|
||||
describe("listMediaController", () => {
|
||||
it("returns empty array when no media exists", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = listMediaUseCase(repo);
|
||||
const controller = listMediaController(useCase);
|
||||
|
||||
const result = await controller({});
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns all media", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
await repo._store(mediaFactory.build());
|
||||
await repo._store(mediaFactory.build());
|
||||
|
||||
const useCase = listMediaUseCase(repo);
|
||||
const controller = listMediaController(useCase);
|
||||
|
||||
const result = await controller({});
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("passes limit and offset to use case", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await repo._store(mediaFactory.build());
|
||||
}
|
||||
|
||||
const useCase = listMediaUseCase(repo);
|
||||
const controller = listMediaController(useCase);
|
||||
|
||||
const result = await controller({ limit: 2, offset: 1 });
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("throws InputParseError on unknown fields (strict schema)", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = listMediaUseCase(repo);
|
||||
const controller = listMediaController(useCase);
|
||||
|
||||
await expect(controller({ unknownField: 1 })).rejects.toThrow(
|
||||
InputParseError,
|
||||
);
|
||||
});
|
||||
|
||||
it("throws InputParseError when limit is not a positive integer", async () => {
|
||||
const repo = new MockMediaRepository();
|
||||
const useCase = listMediaUseCase(repo);
|
||||
const controller = listMediaController(useCase);
|
||||
|
||||
await expect(controller({ limit: -1 })).rejects.toThrow(InputParseError);
|
||||
});
|
||||
});
|
||||
@@ -1,23 +0,0 @@
|
||||
import { InputParseError } from "../../entities/errors/common";
|
||||
import {
|
||||
listMediaInputSchema,
|
||||
type ListMediaOutput,
|
||||
type IListMediaUseCase,
|
||||
} from "../../application/use-cases/list-media.use-case";
|
||||
|
||||
function presenter(value: ListMediaOutput) {
|
||||
return value;
|
||||
}
|
||||
|
||||
export type IListMediaController = ReturnType<typeof listMediaController>;
|
||||
|
||||
export const listMediaController =
|
||||
(listMediaUseCase: IListMediaUseCase) =>
|
||||
async (input: unknown): Promise<ReturnType<typeof presenter>> => {
|
||||
const parsed = listMediaInputSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new InputParseError("Invalid list-media input", { cause: parsed.error });
|
||||
}
|
||||
const result = await listMediaUseCase(parsed.data);
|
||||
return presenter(result);
|
||||
};
|
||||
@@ -1,4 +0,0 @@
|
||||
// Media has no React Query option builders today. This file is the
|
||||
// public UI surface for future components and queries — extend rather
|
||||
// than re-add to root index.ts.
|
||||
export {};
|
||||
@@ -1,83 +0,0 @@
|
||||
// Feature-level test: exercises the full slice
|
||||
// use case factory chain → mock repo
|
||||
// Tests the full dependency chain via direct injection (no container rebinding).
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { MockMediaRepository } from "../src/infrastructure/repositories/media.repository.mock";
|
||||
import { getMediaUseCase } from "../src/application/use-cases/get-media.use-case";
|
||||
import { listMediaUseCase } from "../src/application/use-cases/list-media.use-case";
|
||||
import { deleteMediaUseCase } from "../src/application/use-cases/delete-media.use-case";
|
||||
import { getMediaController } from "../src/interface-adapters/controllers/get-media.controller";
|
||||
import { listMediaController } from "../src/interface-adapters/controllers/list-media.controller";
|
||||
import { deleteMediaController } from "../src/interface-adapters/controllers/delete-media.controller";
|
||||
import { MediaNotFoundError } from "../src/entities/errors/media";
|
||||
import { mediaFactory } from "../src/__factories__/media.factory";
|
||||
|
||||
describe("media feature: end-to-end via direct injection", () => {
|
||||
function buildChain() {
|
||||
const repo = new MockMediaRepository();
|
||||
const getUC = getMediaUseCase(repo);
|
||||
const listUC = listMediaUseCase(repo);
|
||||
const deleteUC = deleteMediaUseCase(repo);
|
||||
const getCtrl = getMediaController(getUC);
|
||||
const listCtrl = listMediaController(listUC);
|
||||
const deleteCtrl = deleteMediaController(deleteUC);
|
||||
return { repo, getCtrl, listCtrl, deleteCtrl };
|
||||
}
|
||||
|
||||
it("listMedia returns empty array initially", async () => {
|
||||
const { listCtrl } = buildChain();
|
||||
const result = await listCtrl({});
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("stores media and retrieves it by id", async () => {
|
||||
const { repo, getCtrl } = buildChain();
|
||||
const seed = mediaFactory.build({ id: "feat-1" });
|
||||
await repo._store(seed);
|
||||
|
||||
const result = await getCtrl({ id: "feat-1" });
|
||||
expect(result.id).toBe("feat-1");
|
||||
expect(result.alt).toBe(seed.alt);
|
||||
});
|
||||
|
||||
it("listMedia returns all stored media", async () => {
|
||||
const { repo, listCtrl } = buildChain();
|
||||
await repo._store(mediaFactory.build());
|
||||
await repo._store(mediaFactory.build());
|
||||
await repo._store(mediaFactory.build());
|
||||
|
||||
const result = await listCtrl({});
|
||||
expect(result).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("deleteMedia removes media so it can no longer be retrieved", async () => {
|
||||
const { repo, getCtrl, deleteCtrl } = buildChain();
|
||||
const seed = mediaFactory.build({ id: "feat-del" });
|
||||
await repo._store(seed);
|
||||
|
||||
await deleteCtrl({ id: "feat-del" });
|
||||
|
||||
await expect(getCtrl({ id: "feat-del" })).rejects.toThrow(MediaNotFoundError);
|
||||
});
|
||||
|
||||
it("getMediaController throws MediaNotFoundError for missing id", async () => {
|
||||
const { getCtrl } = buildChain();
|
||||
await expect(getCtrl({ id: "does-not-exist" })).rejects.toBeInstanceOf(MediaNotFoundError);
|
||||
});
|
||||
|
||||
it("deleteMediaController throws MediaNotFoundError for missing id", async () => {
|
||||
const { deleteCtrl } = buildChain();
|
||||
await expect(deleteCtrl({ id: "does-not-exist" })).rejects.toBeInstanceOf(MediaNotFoundError);
|
||||
});
|
||||
|
||||
it("listMedia with limit respects pagination", async () => {
|
||||
const { repo, listCtrl } = buildChain();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await repo._store(mediaFactory.build());
|
||||
}
|
||||
|
||||
const result = await listCtrl({ limit: 3 });
|
||||
expect(result).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"extends": "@repo/core-typescript/base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": ".",
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"jsx": "preserve",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*", "tests/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"extends": ["//"],
|
||||
"tags": ["feature"]
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import path from "node:path";
|
||||
import { mergeConfig } from "vitest/config";
|
||||
import { nodeVitestConfig } from "@repo/core-typescript/vitest.base.node";
|
||||
import {
|
||||
DEFAULT_COVERAGE_BANDS,
|
||||
vitestThresholdsFromBands,
|
||||
} from "@repo/core-shared/conformance/coverage";
|
||||
|
||||
// Coverage thresholds derived from DEFAULT_COVERAGE_BANDS via the shared
|
||||
// helper (ADR-020). The feature.manifest.ts `coverage.bands` section
|
||||
// declares these for boot-time `assertFeatureConformance`. Edit the
|
||||
// manifest when adjusting per-feature bands.
|
||||
export default mergeConfig(nodeVitestConfig, {
|
||||
test: {
|
||||
coverage: {
|
||||
exclude: [
|
||||
// DI bootstrap — wires InversifyJS at app startup; not unit-testable
|
||||
"src/di/bind-production.ts",
|
||||
// Pure TypeScript interface files — not executable
|
||||
"src/application/repositories/**",
|
||||
"src/application/services/**",
|
||||
// Payload CMS collection config — declarative data, tested via Payload integration
|
||||
"src/integrations/cms/**",
|
||||
// React Query option builders — integration-tested in apps
|
||||
"src/ui/**",
|
||||
],
|
||||
thresholds: vitestThresholdsFromBands(DEFAULT_COVERAGE_BANDS),
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
alias: { "@": path.resolve(__dirname, "./src") },
|
||||
},
|
||||
});
|
||||
@@ -16,11 +16,6 @@ export const header: GlobalConfig = {
|
||||
group: "Navigation",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "logo",
|
||||
type: "upload",
|
||||
relationTo: "media",
|
||||
},
|
||||
{
|
||||
name: "items",
|
||||
type: "array",
|
||||
|
||||
49
pnpm-lock.yaml
generated
49
pnpm-lock.yaml
generated
@@ -191,9 +191,6 @@ importers:
|
||||
"@repo/marketing-pages":
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/marketing-pages
|
||||
"@repo/media":
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/media
|
||||
"@repo/navigation":
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/navigation
|
||||
@@ -371,9 +368,6 @@ importers:
|
||||
"@repo/marketing-pages":
|
||||
specifier: workspace:*
|
||||
version: link:../marketing-pages
|
||||
"@repo/media":
|
||||
specifier: workspace:*
|
||||
version: link:../media
|
||||
"@repo/navigation":
|
||||
specifier: workspace:*
|
||||
version: link:../navigation
|
||||
@@ -466,9 +460,6 @@ importers:
|
||||
"@repo/marketing-pages":
|
||||
specifier: workspace:*
|
||||
version: link:../marketing-pages
|
||||
"@repo/media":
|
||||
specifier: workspace:*
|
||||
version: link:../media
|
||||
"@repo/navigation":
|
||||
specifier: workspace:*
|
||||
version: link:../navigation
|
||||
@@ -947,46 +938,6 @@ importers:
|
||||
specifier: ^3.1.0
|
||||
version: 3.2.4(@types/debug@4.1.13)(@types/node@22.19.17)(happy-dom@20.8.9)(jiti@2.7.0)(jsdom@25.0.1)(lightningcss@1.32.0)(sass@1.99.0)(terser@5.46.2)(tsx@4.21.0)(yaml@2.9.0)
|
||||
|
||||
packages/media:
|
||||
dependencies:
|
||||
"@repo/core-shared":
|
||||
specifier: workspace:*
|
||||
version: link:../core-shared
|
||||
"@trpc/server":
|
||||
specifier: ^11.0.0
|
||||
version: 11.16.0(typescript@5.9.3)
|
||||
inversify:
|
||||
specifier: ^6.2.0
|
||||
version: 6.2.2(reflect-metadata@0.2.2)
|
||||
payload:
|
||||
specifier: ^3.14.0
|
||||
version: 3.81.0(graphql@16.13.2)(typescript@5.9.3)
|
||||
reflect-metadata:
|
||||
specifier: ^0.2.2
|
||||
version: 0.2.2
|
||||
zod:
|
||||
specifier: ^3.24.0
|
||||
version: 3.25.76
|
||||
devDependencies:
|
||||
"@repo/core-eslint":
|
||||
specifier: workspace:*
|
||||
version: link:../core-eslint
|
||||
"@repo/core-testing":
|
||||
specifier: workspace:*
|
||||
version: link:../core-testing
|
||||
"@repo/core-typescript":
|
||||
specifier: workspace:*
|
||||
version: link:../core-typescript
|
||||
"@types/node":
|
||||
specifier: ^22.0.0
|
||||
version: 22.19.17
|
||||
"@vitest/coverage-v8":
|
||||
specifier: ^3.2.4
|
||||
version: 3.2.4(vitest@3.2.4(@types/debug@4.1.13)(@types/node@22.19.17)(happy-dom@20.8.9)(jiti@2.7.0)(jsdom@25.0.1)(lightningcss@1.32.0)(sass@1.99.0)(terser@5.46.2)(tsx@4.21.0)(yaml@2.9.0))
|
||||
vitest:
|
||||
specifier: ^3.1.0
|
||||
version: 3.2.4(@types/debug@4.1.13)(@types/node@22.19.17)(happy-dom@20.8.9)(jiti@2.7.0)(jsdom@25.0.1)(lightningcss@1.32.0)(sass@1.99.0)(terser@5.46.2)(tsx@4.21.0)(yaml@2.9.0)
|
||||
|
||||
packages/navigation:
|
||||
dependencies:
|
||||
"@repo/core-shared":
|
||||
|
||||
@@ -22,12 +22,6 @@
|
||||
"@repo/auth": ["./packages/auth/src/index.ts"],
|
||||
"@repo/auth/cms": ["./packages/auth/src/integrations/cms/index.ts"],
|
||||
"@repo/auth/api": ["./packages/auth/src/integrations/api/router.ts"],
|
||||
"@repo/media": ["./packages/media/src/index.ts"],
|
||||
"@repo/media/cms": ["./packages/media/src/integrations/cms/index.ts"],
|
||||
"@repo/media/api": ["./packages/media/src/integrations/api/index.ts"],
|
||||
"@repo/media/di/bind-production": [
|
||||
"./packages/media/src/di/bind-production.ts"
|
||||
],
|
||||
"@repo/marketing-pages": ["./packages/marketing-pages/src/index.ts"],
|
||||
"@repo/marketing-pages/cms": [
|
||||
"./packages/marketing-pages/src/integrations/cms/index.ts"
|
||||
|
||||
@@ -63,12 +63,7 @@ describe("e2e: core-package events", () => {
|
||||
|
||||
// Strip @repo/core-events from feature package.json files so pnpm install
|
||||
// succeeds without the package being present (simulating the post-removal state).
|
||||
const featurePackages = [
|
||||
"auth",
|
||||
"media",
|
||||
"marketing-pages",
|
||||
"navigation",
|
||||
];
|
||||
const featurePackages = ["auth", "marketing-pages", "navigation"];
|
||||
for (const pkg of featurePackages) {
|
||||
const pkgJson = join(tmp, "packages", pkg, "package.json");
|
||||
stripCoreEventsDep(pkgJson);
|
||||
|
||||
Reference in New Issue
Block a user