Initial commit
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import { describe } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { MockArticlesRepository } from "@/infrastructure/repositories/articles.repository.mock";
|
||||
import { articlesRepositoryContract } from "@/__contracts__/articles-repository.contract";
|
||||
|
||||
describe("MockArticlesRepository", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
articlesRepositoryContract.run(
|
||||
() => new MockArticlesRepository(tracer),
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import "reflect-metadata";
|
||||
import { injectable } from "inversify";
|
||||
import {
|
||||
NoopTracer,
|
||||
NoopLogger,
|
||||
type ITracer,
|
||||
type ILogger,
|
||||
} from "@repo/core-shared/instrumentation";
|
||||
|
||||
import type { IArticlesRepository } from "../../application/repositories/articles.repository.interface";
|
||||
import type { Article } from "../../entities/models/article";
|
||||
|
||||
@injectable()
|
||||
export class MockArticlesRepository implements IArticlesRepository {
|
||||
private _articles: Article[] = [];
|
||||
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 getArticle(id: string): Promise<Article | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "articles.getArticle", op: "repository", attributes: { id } },
|
||||
async (span) => {
|
||||
const found = this._articles.find((a) => a.id === id);
|
||||
span.setAttribute("found", Boolean(found));
|
||||
return found;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getArticleBySlug(slug: string): Promise<Article | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "articles.getArticleBySlug", op: "repository", attributes: { slug } },
|
||||
async (span) => {
|
||||
const found = this._articles.find((a) => a.slug === slug);
|
||||
span.setAttribute("found", Boolean(found));
|
||||
return found;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getArticles(options?: {
|
||||
status?: string;
|
||||
authorId?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<Article[]> {
|
||||
return this.tracer.startSpan(
|
||||
{
|
||||
name: "articles.getArticles",
|
||||
op: "repository",
|
||||
attributes: {
|
||||
status: options?.status ?? null,
|
||||
authorId: options?.authorId ?? null,
|
||||
limit: options?.limit ?? null,
|
||||
offset: options?.offset ?? null,
|
||||
},
|
||||
},
|
||||
async (span) => {
|
||||
let result = [...this._articles];
|
||||
if (options?.status) {
|
||||
result = result.filter((a) => a.status === options.status);
|
||||
}
|
||||
if (options?.authorId) {
|
||||
result = result.filter((a) => a.authorId === options.authorId);
|
||||
}
|
||||
const offset = options?.offset ?? 0;
|
||||
const limit = options?.limit ?? 50;
|
||||
const sliced = result.slice(offset, offset + limit);
|
||||
span.setAttribute("count", sliced.length);
|
||||
return sliced;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async createArticle(input: Article): Promise<Article> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "articles.createArticle", op: "repository", attributes: { slug: input.slug } },
|
||||
async (span) => {
|
||||
this._articles.push(input);
|
||||
span.setAttribute("id", input.id);
|
||||
return input;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async updateArticle(
|
||||
id: string,
|
||||
input: Partial<Article>,
|
||||
): Promise<Article | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "articles.updateArticle", op: "repository", attributes: { id } },
|
||||
async (span) => {
|
||||
const idx = this._articles.findIndex((a) => a.id === id);
|
||||
if (idx === -1) {
|
||||
span.setAttribute("found", false);
|
||||
return undefined;
|
||||
}
|
||||
const merged = { ...this._articles[idx]!, ...input, id } as Article;
|
||||
this._articles[idx] = merged;
|
||||
span.setAttribute("found", true);
|
||||
return merged;
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
RecordingTracer,
|
||||
RecordingLogger,
|
||||
} from "@repo/core-testing/instrumentation";
|
||||
import { MockArticlesRepository } from "@/infrastructure/repositories/articles.repository.mock";
|
||||
|
||||
// Mock repo also wraps in spans; easier to assert without booting Payload.
|
||||
describe("MockArticlesRepository emits spans", () => {
|
||||
it("getArticles emits one span with op='repository'", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const logger = new RecordingLogger();
|
||||
const repo = new MockArticlesRepository(tracer, logger);
|
||||
await repo.getArticles({ limit: 10 });
|
||||
expect(tracer.spans).toHaveLength(1);
|
||||
expect(tracer.spans[0]).toMatchObject({
|
||||
name: "articles.getArticles",
|
||||
op: "repository",
|
||||
});
|
||||
expect(tracer.spans[0]!.attributes).toMatchObject({ limit: 10 });
|
||||
});
|
||||
|
||||
it("createArticle emits a span with slug attribute", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const repo = new MockArticlesRepository(tracer);
|
||||
await repo.createArticle({
|
||||
id: "a1",
|
||||
title: "T",
|
||||
slug: "t",
|
||||
content: null,
|
||||
status: "draft",
|
||||
authorId: "u1",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
expect(tracer.findSpan("articles.createArticle")).toBeDefined();
|
||||
expect(tracer.findSpan("articles.createArticle")!.attributes.slug).toBe(
|
||||
"t",
|
||||
);
|
||||
});
|
||||
|
||||
it("getArticle records found=false for missing id", async () => {
|
||||
const tracer = new RecordingTracer();
|
||||
const repo = new MockArticlesRepository(tracer);
|
||||
await repo.getArticle("missing");
|
||||
expect(tracer.spans[0]!.attributes.found).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import { RecordingTracer } from "@repo/core-testing/instrumentation";
|
||||
import { ArticlesRepository } from "@/infrastructure/repositories/articles.repository";
|
||||
import { articlesRepositoryContract } from "@/__contracts__/articles-repository.contract";
|
||||
import { stubPayloadConfig } from "@repo/core-testing/payload/stub-config";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory Payload stub used by both the contract suite and impl-specific tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildPayloadStub() {
|
||||
const store = new Map<string, Record<string, unknown>>();
|
||||
|
||||
return {
|
||||
create: vi.fn(
|
||||
async ({
|
||||
data,
|
||||
}: {
|
||||
collection: string;
|
||||
data: Record<string, unknown>;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
// Payload assigns an id; here we require the data to carry one
|
||||
// (the repository passes `id` via the mapped domain object implicitly
|
||||
// through the Article — we expose the mapped doc back from createArticle).
|
||||
// The stub returns the data as-is so the mapDoc function can work.
|
||||
const doc = { id: `stub-${store.size + 1}`, ...data };
|
||||
store.set(String(doc.id), doc);
|
||||
return doc;
|
||||
},
|
||||
),
|
||||
find: vi.fn(
|
||||
async ({
|
||||
where,
|
||||
limit,
|
||||
}: {
|
||||
collection: string;
|
||||
where?: {
|
||||
slug?: { equals: string };
|
||||
status?: { equals: string };
|
||||
author?: { 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 (where?.author) {
|
||||
docs = docs.filter((d) => d.author === where.author?.equals);
|
||||
}
|
||||
if (limit !== undefined) {
|
||||
docs = docs.slice(0, limit);
|
||||
}
|
||||
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;
|
||||
},
|
||||
),
|
||||
update: vi.fn(
|
||||
async ({
|
||||
id,
|
||||
data,
|
||||
}: {
|
||||
collection: string;
|
||||
id: string;
|
||||
data: Record<string, unknown>;
|
||||
overrideAccess?: boolean;
|
||||
}) => {
|
||||
const existing = store.get(String(id));
|
||||
if (!existing) {
|
||||
const err = Object.assign(new Error(`Not found: ${id}`), { status: 404 });
|
||||
throw err;
|
||||
}
|
||||
const updated = { ...existing, ...data };
|
||||
store.set(String(id), updated);
|
||||
return updated;
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("payload", () => ({
|
||||
getPayload: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Contract suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("ArticlesRepository", () => {
|
||||
describe("contract", () => {
|
||||
const tracer = new RecordingTracer();
|
||||
articlesRepositoryContract.run(
|
||||
async () => {
|
||||
const stub = buildPayloadStub();
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue(stub);
|
||||
return new ArticlesRepository(stubPayloadConfig, tracer);
|
||||
},
|
||||
{ tracer: () => tracer },
|
||||
);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Impl-specific tests: Payload doc → domain mapping
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
describe("Payload doc → domain mapping", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("maps a Payload doc to a domain Article on getArticleBySlug", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
const findMock = vi.fn().mockResolvedValue({
|
||||
docs: [
|
||||
{
|
||||
id: "p-123",
|
||||
title: "Hello",
|
||||
slug: "hello",
|
||||
content: { type: "doc", children: [] },
|
||||
status: "published",
|
||||
author: "u1",
|
||||
createdAt: "2026-05-04T12:00:00.000Z",
|
||||
updatedAt: "2026-05-04T12:00:00.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
find: findMock,
|
||||
});
|
||||
|
||||
const repo = new ArticlesRepository(stubPayloadConfig);
|
||||
const result = await repo.getArticleBySlug("hello");
|
||||
|
||||
expect(findMock).toHaveBeenCalledWith({
|
||||
collection: "articles",
|
||||
where: { slug: { equals: "hello" } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(result?.id).toBe("p-123");
|
||||
expect(result?.slug).toBe("hello");
|
||||
expect(result?.status).toBe("published");
|
||||
expect(result?.authorId).toBe("u1");
|
||||
expect(result?.createdAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("returns undefined when slug is not found", async () => {
|
||||
const { getPayload } = await import("payload");
|
||||
(getPayload as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
find: vi.fn().mockResolvedValue({ docs: [] }),
|
||||
});
|
||||
|
||||
const repo = new ArticlesRepository(stubPayloadConfig);
|
||||
const result = await repo.getArticleBySlug("missing");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
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 { IArticlesRepository } from "../../application/repositories/articles.repository.interface";
|
||||
import type { Article } from "../../entities/models/article";
|
||||
|
||||
type PayloadArticleDoc = {
|
||||
id: string | number;
|
||||
title?: string | null;
|
||||
slug?: string | null;
|
||||
content?: unknown;
|
||||
status?: string | null;
|
||||
author?: string | number | { id: string | number } | null;
|
||||
createdAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
};
|
||||
|
||||
function mapDoc(doc: PayloadArticleDoc): Article {
|
||||
const authorId =
|
||||
typeof doc.author === "object" && doc.author !== null
|
||||
? String(doc.author.id)
|
||||
: doc.author != null
|
||||
? String(doc.author)
|
||||
: "";
|
||||
return {
|
||||
id: String(doc.id),
|
||||
title: doc.title ?? "",
|
||||
slug: doc.slug ?? "",
|
||||
content: doc.content ?? null,
|
||||
status: doc.status === "published" ? "published" : "draft",
|
||||
authorId,
|
||||
createdAt: doc.createdAt ? new Date(doc.createdAt) : new Date(0),
|
||||
updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : new Date(0),
|
||||
};
|
||||
}
|
||||
|
||||
const FEATURE = "blog" as const;
|
||||
const REPO = "articles" as const;
|
||||
|
||||
@injectable()
|
||||
export class ArticlesRepository implements IArticlesRepository {
|
||||
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 getArticle(id: string): Promise<Article | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "articles.getArticle", op: "repository", attributes: { id } },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const doc = await payload.findByID({
|
||||
collection: "articles",
|
||||
id,
|
||||
overrideAccess: true,
|
||||
});
|
||||
span.setAttribute("found", true);
|
||||
return mapDoc(doc as PayloadArticleDoc);
|
||||
} catch (err) {
|
||||
// Payload throws on not-found; treat as undefined per existing semantics
|
||||
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: "getArticle" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getArticleBySlug(slug: string): Promise<Article | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "articles.getArticleBySlug", op: "repository", attributes: { slug } },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const result = await payload.find({
|
||||
collection: "articles",
|
||||
where: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const doc = result.docs[0] as PayloadArticleDoc | undefined;
|
||||
span.setAttribute("found", Boolean(doc));
|
||||
return doc ? mapDoc(doc) : undefined;
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getArticleBySlug" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getArticles(options?: {
|
||||
status?: string;
|
||||
authorId?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<Article[]> {
|
||||
return this.tracer.startSpan(
|
||||
{
|
||||
name: "articles.getArticles",
|
||||
op: "repository",
|
||||
attributes: {
|
||||
status: options?.status ?? null,
|
||||
authorId: options?.authorId ?? 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 };
|
||||
if (options?.authorId) where.author = { equals: options.authorId };
|
||||
|
||||
const result = await payload.find({
|
||||
collection: "articles",
|
||||
where: where as never,
|
||||
limit: options?.limit ?? 50,
|
||||
page: options?.offset
|
||||
? Math.floor(options.offset / (options.limit ?? 50)) + 1
|
||||
: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
span.setAttribute("count", result.docs.length);
|
||||
return result.docs.map((d) => mapDoc(d as PayloadArticleDoc));
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "getArticles" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async createArticle(input: Article): Promise<Article> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "articles.createArticle", op: "repository", attributes: { slug: input.slug } },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const created = await payload.create({
|
||||
collection: "articles",
|
||||
data: {
|
||||
title: input.title,
|
||||
slug: input.slug,
|
||||
content: input.content,
|
||||
status: input.status,
|
||||
author: input.authorId,
|
||||
} as never,
|
||||
overrideAccess: true,
|
||||
});
|
||||
span.setAttribute("id", String((created as PayloadArticleDoc).id));
|
||||
return mapDoc(created as PayloadArticleDoc);
|
||||
} catch (err) {
|
||||
this.logger.captureException(err, {
|
||||
tags: { feature: FEATURE, repo: REPO, method: "createArticle" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async updateArticle(
|
||||
id: string,
|
||||
input: Partial<Article>,
|
||||
): Promise<Article | undefined> {
|
||||
return this.tracer.startSpan(
|
||||
{ name: "articles.updateArticle", op: "repository", attributes: { id } },
|
||||
async (span) => {
|
||||
try {
|
||||
const payload = await getPayload({ config: this.config });
|
||||
const updated = await payload.update({
|
||||
collection: "articles",
|
||||
id,
|
||||
data: {
|
||||
...(input.title !== undefined && { title: input.title }),
|
||||
...(input.slug !== undefined && { slug: input.slug }),
|
||||
...(input.content !== undefined && { content: input.content }),
|
||||
...(input.status !== undefined && { status: input.status }),
|
||||
...(input.authorId !== undefined && { author: input.authorId }),
|
||||
} as never,
|
||||
overrideAccess: true,
|
||||
});
|
||||
span.setAttribute("found", true);
|
||||
return mapDoc(updated as PayloadArticleDoc);
|
||||
} 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: "updateArticle" },
|
||||
});
|
||||
span.setStatus("error", err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user