Initial commit
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
import { describe } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { MockPagesRepository } from "@/infrastructure/repositories/pages.repository.mock";
|
||||
import {
|
||||
pagesRepositoryContract,
|
||||
CONTRACT_PAGES_SEED,
|
||||
} from "@/__contracts__/pages-repository.contract";
|
||||
|
||||
describe("MockPagesRepository", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
// Pre-seed with the contract fixtures so the contract assertions find what
|
||||
// they expect (an "about" published page and a "draft-page" draft page).
|
||||
pagesRepositoryContract.run(
|
||||
() => new MockPagesRepository(CONTRACT_PAGES_SEED, tracer),
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { IPagesRepository } from "../../application/repositories/pages.repository.interface";
|
||||
import type { Page } from "../../entities/models/page";
|
||||
|
||||
const SEED_DATE = new Date("2026-01-01T00:00:00.000Z");
|
||||
|
||||
const DEFAULT_SEED: Page[] = [
|
||||
{
|
||||
id: "p1",
|
||||
title: "About",
|
||||
slug: "about",
|
||||
hero: { heading: "About us" },
|
||||
layout: [],
|
||||
status: "published",
|
||||
publishedAt: SEED_DATE,
|
||||
seo: { title: "About — My App" },
|
||||
createdAt: SEED_DATE,
|
||||
updatedAt: SEED_DATE,
|
||||
},
|
||||
];
|
||||
|
||||
@injectable()
|
||||
export class MockPagesRepository implements IPagesRepository {
|
||||
private _pages: Page[];
|
||||
private tracer: ITracer;
|
||||
private logger: ILogger;
|
||||
|
||||
constructor(
|
||||
initialPages: Page[] = DEFAULT_SEED,
|
||||
tracer: ITracer = new NoopTracer(),
|
||||
logger: ILogger = new NoopLogger(),
|
||||
) {
|
||||
this._pages = [...initialPages];
|
||||
this.tracer = tracer;
|
||||
this.logger = logger;
|
||||
void this.logger; // currently unused; reserved for future mock-thrown captures
|
||||
}
|
||||
|
||||
async getPageBySlug(slug: string): Promise<Page | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "pages.getPageBySlug", op: "repository", attributes: { slug } },
|
||||
async (span) => {
|
||||
const found = this._pages.find((p) => p.slug === slug);
|
||||
span.setAttribute("found", Boolean(found));
|
||||
return found;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getPages(options?: {
|
||||
status?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<Page[]> {
|
||||
return this.tracer.startSpan(
|
||||
{
|
||||
name: "pages.getPages",
|
||||
op: "repository",
|
||||
attributes: {
|
||||
status: options?.status ?? null,
|
||||
limit: options?.limit ?? null,
|
||||
offset: options?.offset ?? null,
|
||||
},
|
||||
},
|
||||
async (span) => {
|
||||
let result = [...this._pages];
|
||||
if (options?.status) {
|
||||
result = result.filter((p) => p.status === options.status);
|
||||
}
|
||||
const offset = options?.offset ?? 0;
|
||||
const limit = options?.limit ?? 50;
|
||||
const page = result.slice(offset, offset + limit);
|
||||
span.setAttribute("count", page.length);
|
||||
return page;
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
RecordingTracer,
|
||||
RecordingLogger,
|
||||
} from "@repo/core-testing/instrumentation";
|
||||
import { MockPagesRepository } from "@/infrastructure/repositories/pages.repository.mock";
|
||||
|
||||
// Mock repo also wraps in spans.
|
||||
describe("MockPagesRepository emits spans", () => {
|
||||
it("getPageBySlug emits one span with op='repository'", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const logger = new RecordingLogger();
|
||||
const repo = new MockPagesRepository([], tracer, logger);
|
||||
await repo.getPageBySlug("about");
|
||||
expect(tracer.spans).toHaveLength(1);
|
||||
expect(tracer.spans[0]).toMatchObject({
|
||||
name: "pages.getPageBySlug",
|
||||
op: "repository",
|
||||
});
|
||||
expect(tracer.spans[0]!.attributes.slug).toBe("about");
|
||||
expect(tracer.spans[0]!.attributes.found).toBe(false);
|
||||
});
|
||||
|
||||
it("getPages emits a span with count attribute", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const repo = new MockPagesRepository(undefined, tracer);
|
||||
await repo.getPages({ limit: 10 });
|
||||
expect(tracer.findSpan("pages.getPages")).toBeDefined();
|
||||
expect(tracer.findSpan("pages.getPages")!.attributes.limit).toBe(10);
|
||||
expect(
|
||||
tracer.findSpan("pages.getPages")!.attributes.count,
|
||||
).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, vi } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { PagesRepository } from "@/infrastructure/repositories/pages.repository";
|
||||
import {
|
||||
pagesRepositoryContract,
|
||||
CONTRACT_PAGES_SEED,
|
||||
} from "@/__contracts__/pages-repository.contract";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
import type { Page } from "@/entities/models/page";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory Payload stub for pages (read-only collection)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildPayloadPagesStub(seed: Page[]) {
|
||||
const store = new Map<string, Record<string, unknown>>(
|
||||
seed.map((p) => [
|
||||
p.id,
|
||||
{
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
slug: p.slug,
|
||||
hero: p.hero
|
||||
? {
|
||||
heading: p.hero.heading,
|
||||
subheading: p.hero.subheading,
|
||||
}
|
||||
: null,
|
||||
layout: p.layout,
|
||||
status: p.status,
|
||||
publishedAt: p.publishedAt ? p.publishedAt.toISOString() : null,
|
||||
seo: p.seo ? { title: p.seo.title, description: p.seo.description } : null,
|
||||
createdAt: p.createdAt.toISOString(),
|
||||
updatedAt: p.updatedAt.toISOString(),
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
return {
|
||||
find: vi.fn(
|
||||
async ({
|
||||
where,
|
||||
limit,
|
||||
}: {
|
||||
collection: string;
|
||||
where?: { slug?: { equals: string }; status?: { equals: string } };
|
||||
limit?: number;
|
||||
page?: number;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
let docs = Array.from(store.values());
|
||||
if (where?.slug) {
|
||||
docs = docs.filter((d) => d.slug === where.slug?.equals);
|
||||
}
|
||||
if (where?.status) {
|
||||
docs = docs.filter((d) => d.status === where.status?.equals);
|
||||
}
|
||||
if (limit !== undefined) {
|
||||
docs = docs.slice(0, limit);
|
||||
}
|
||||
return { docs };
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("payload", () => ({
|
||||
getPayload: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Contract suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PagesRepository", () => {
|
||||
describe("contract", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
pagesRepositoryContract.run(
|
||||
async () => {
|
||||
const stub = buildPayloadPagesStub(CONTRACT_PAGES_SEED);
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue(stub);
|
||||
return new PagesRepository(stubPayloadConfig, tracer);
|
||||
},
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
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 { IPagesRepository } from "../../application/repositories/pages.repository.interface";
|
||||
import type { Page } from "../../entities/models/page";
|
||||
|
||||
type PayloadPageDoc = {
|
||||
id: string | number;
|
||||
title?: string | null;
|
||||
slug?: string | null;
|
||||
hero?:
|
||||
| {
|
||||
heading?: string | null;
|
||||
subheading?: string | null;
|
||||
image?: string | number | { id: string | number } | null;
|
||||
}
|
||||
| null;
|
||||
layout?: unknown[] | null;
|
||||
status?: string | null;
|
||||
publishedAt?: string | null;
|
||||
seo?: { title?: string | null; description?: string | null } | null;
|
||||
createdAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
};
|
||||
|
||||
function mapDoc(doc: PayloadPageDoc): Page {
|
||||
const imageId =
|
||||
doc.hero && typeof doc.hero.image === "object" && doc.hero.image !== null
|
||||
? String(doc.hero.image.id)
|
||||
: doc.hero?.image != null
|
||||
? String(doc.hero.image)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: String(doc.id),
|
||||
title: doc.title ?? "",
|
||||
slug: doc.slug ?? "",
|
||||
hero: {
|
||||
heading: doc.hero?.heading ?? "",
|
||||
subheading: doc.hero?.subheading ?? undefined,
|
||||
imageId,
|
||||
},
|
||||
layout: doc.layout ?? [],
|
||||
status: doc.status === "published" ? "published" : "draft",
|
||||
publishedAt: doc.publishedAt ? new Date(doc.publishedAt) : null,
|
||||
seo: {
|
||||
title: doc.seo?.title ?? "",
|
||||
description: doc.seo?.description ?? undefined,
|
||||
},
|
||||
createdAt: doc.createdAt ? new Date(doc.createdAt) : new Date(0),
|
||||
updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : new Date(0),
|
||||
};
|
||||
}
|
||||
|
||||
const FEATURE = "marketing-pages" as const;
|
||||
const REPO = "pages" as const;
|
||||
|
||||
@injectable()
|
||||
export class PagesRepository implements IPagesRepository {
|
||||
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 getPageBySlug(slug: string): Promise<Page | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "pages.getPageBySlug", op: "repository", attributes: { slug } },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const result = await payload.find({
|
||||
collection: "pages",
|
||||
where: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const doc = result.docs[0] as PayloadPageDoc | undefined;
|
||||
span.setAttribute("found", Boolean(doc));
|
||||
return doc ? mapDoc(doc) : undefined;
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getPageBySlug" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getPages(options?: {
|
||||
status?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<Page[]> {
|
||||
return this.tracer.startSpan(
|
||||
{
|
||||
name: "pages.getPages",
|
||||
op: "repository",
|
||||
attributes: {
|
||||
status: options?.status ?? null,
|
||||
limit: options?.limit ?? null,
|
||||
offset: options?.offset ?? null,
|
||||
},
|
||||
},
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const where: Record<string, { equals: string }> = {};
|
||||
if (options?.status) where.status = { equals: options.status };
|
||||
const result = await payload.find({
|
||||
collection: "pages",
|
||||
where: where as never,
|
||||
limit: options?.limit ?? 50,
|
||||
page: options?.offset
|
||||
? Math.floor(options.offset / (options.limit ?? 50)) + 1
|
||||
: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const pages = result.docs.map((d) => mapDoc(d as PayloadPageDoc));
|
||||
span.setAttribute("count", pages.length);
|
||||
return pages;
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getPages" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { MockSiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository.mock";
|
||||
import { siteSettingsRepositoryContract } from "@/__contracts__/site-settings-repository.contract";
|
||||
|
||||
describe("MockSiteSettingsRepository", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
siteSettingsRepositoryContract.run(
|
||||
() => new MockSiteSettingsRepository(tracer),
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { ISiteSettingsRepository } from "../../application/repositories/site-settings.repository.interface";
|
||||
import type { SiteSettings } from "../../entities/models/site-settings";
|
||||
|
||||
@injectable()
|
||||
export class MockSiteSettingsRepository implements ISiteSettingsRepository {
|
||||
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
|
||||
}
|
||||
|
||||
async getSiteSettings(): Promise<SiteSettings> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "site-settings.getSiteSettings", op: "repository", attributes: {} },
|
||||
async (span) => {
|
||||
span.setAttribute("found", true);
|
||||
return {
|
||||
siteName: "My App",
|
||||
siteDescription: "A vertical-feature monorepo template",
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
RecordingTracer,
|
||||
RecordingLogger,
|
||||
} from "@repo/core-testing/instrumentation";
|
||||
import { MockSiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository.mock";
|
||||
|
||||
// Mock repo also wraps in spans.
|
||||
describe("MockSiteSettingsRepository emits spans", () => {
|
||||
it("getSiteSettings emits one span with op='repository'", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const logger = new RecordingLogger();
|
||||
const repo = new MockSiteSettingsRepository(tracer, logger);
|
||||
await repo.getSiteSettings();
|
||||
expect(tracer.spans).toHaveLength(1);
|
||||
expect(tracer.spans[0]).toMatchObject({
|
||||
name: "site-settings.getSiteSettings",
|
||||
op: "repository",
|
||||
});
|
||||
expect(tracer.spans[0]!.attributes.found).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, vi } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { SiteSettingsRepository } from "@/infrastructure/repositories/site-settings.repository";
|
||||
import { siteSettingsRepositoryContract } from "@/__contracts__/site-settings-repository.contract";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory Payload stub for site-settings (Global)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildSiteSettingsStub() {
|
||||
const globalData: Record<string, unknown> = {
|
||||
siteName: "Contract Site",
|
||||
siteDescription: "A site for contract testing",
|
||||
};
|
||||
|
||||
return {
|
||||
findGlobal: vi.fn(async () => {
|
||||
return { ...globalData };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("payload", () => ({
|
||||
getPayload: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Contract suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SiteSettingsRepository", () => {
|
||||
describe("contract", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
siteSettingsRepositoryContract.run(
|
||||
async () => {
|
||||
const stub = buildSiteSettingsStub();
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue(stub);
|
||||
return new SiteSettingsRepository(stubPayloadConfig, tracer);
|
||||
},
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
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 { ISiteSettingsRepository } from "../../application/repositories/site-settings.repository.interface";
|
||||
import type { SiteSettings } from "../../entities/models/site-settings";
|
||||
|
||||
type PayloadSiteSettings = {
|
||||
siteName?: string | null;
|
||||
siteDescription?: string | null;
|
||||
};
|
||||
|
||||
const FEATURE = "marketing-pages" as const;
|
||||
const REPO = "site-settings" as const;
|
||||
|
||||
@injectable()
|
||||
export class SiteSettingsRepository implements ISiteSettingsRepository {
|
||||
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 getSiteSettings(): Promise<SiteSettings> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "site-settings.getSiteSettings", op: "repository", attributes: {} },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const doc = (await payload.findGlobal({
|
||||
slug: "site-settings",
|
||||
overrideAccess: true,
|
||||
})) as PayloadSiteSettings;
|
||||
span.setAttribute("found", true);
|
||||
return {
|
||||
siteName: doc.siteName ?? "My App",
|
||||
siteDescription: doc.siteDescription ?? undefined,
|
||||
};
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getSiteSettings" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { RecordingMailerService } from "@/infrastructure/services/recording-mailer.service";
|
||||
|
||||
describe("RecordingMailerService", () => {
|
||||
it("records welcome calls", async () => {
|
||||
const mailer = new RecordingMailerService();
|
||||
await mailer.sendWelcome("u1", "u1@example.com");
|
||||
expect(mailer.sent).toEqual([{ userId: "u1", email: "u1@example.com" }]);
|
||||
});
|
||||
|
||||
it("preserves call order across multiple sends", async () => {
|
||||
const mailer = new RecordingMailerService();
|
||||
await mailer.sendWelcome("u1", "a@x");
|
||||
await mailer.sendWelcome("u2", "b@x");
|
||||
expect(mailer.sent).toEqual([
|
||||
{ userId: "u1", email: "a@x" },
|
||||
{ userId: "u2", email: "b@x" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { IMailerService } from "../../application/services/mailer.service.interface";
|
||||
|
||||
export class RecordingMailerService implements IMailerService {
|
||||
readonly sent: { userId: string; email: string }[] = [];
|
||||
|
||||
async sendWelcome(userId: string, email: string): Promise<void> {
|
||||
this.sent.push({ userId, email });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user