Files
tech-log-frontend/src/features/tech-log/adapters/static/public-query.ts
T

439 lines
14 KiB
TypeScript

import {
projects,
publicRecords,
releases,
type Project,
type ProjectActivity,
type ProjectDecision,
type PublicRecord,
type RecordKind,
type Release,
type HomeFocusItem,
} from "./public-content.ts";
import { projectStageLabel } from "../../domain/public/project-phase-labels.ts";
import type {
LatestRecordEntry,
PublicContentQueries,
PublicTopic,
PublicTopicDetail,
RecordFilters,
} from "../../application/ports/public-content-queries.ts";
/*
포트의 것을 그대로 쓴다. 여기 따로 적어 두었더니 포트에 필터가 하나 늘 때 이쪽만 모르는
상태가 됐고, `satisfies` 는 메서드 매개변수가 bivariant 라 그것을 잡지 못했다.
*/
export type { RecordFilters };
export type SearchablePublicEntity = {
contentType: RecordKind | "PROJECT" | "RELEASE";
title: string;
summary: string;
path: string;
topic?: string;
topics?: ReadonlyArray<string>;
project?: string;
publishedAt?: string;
};
function comparePublishedAt(
left: Pick<PublicRecord, "publishedAt">,
right: Pick<PublicRecord, "publishedAt">,
) {
return right.publishedAt.localeCompare(left.publishedAt);
}
export function listRecords(filters: RecordFilters = {}): PublicRecord[] {
/*
빈 필터는 아무것도 고르지 않는다.
예전에는 빈 값을 비교해도 걸리는 기록이 없어 저절로 빈 목록이 됐다. 개념이 프로젝트 없이
설 수 있게 되면서 `projectSlug` 가 빈 기록이 생겼고, 그때부터 `?project=` 는 "프로젝트가
없는 기록 전부" 를 뜻하게 됐다 — 고르지 않은 것이 고른 것이 되어 버린다.
*/
const hasTopicFilter = filters.topic !== undefined && filters.topic.trim() !== "";
const hasProjectFilter = filters.project !== undefined && filters.project.trim() !== "";
const filtersNothing =
(filters.topic !== undefined && filters.topic.trim() === "") ||
(filters.project !== undefined && filters.project.trim() === "");
if (filtersNothing) return [];
const requestedTopic = filters.topic?.trim().toLocaleLowerCase("ko-KR");
const requestedProject = filters.project
?.trim()
.toLocaleLowerCase("ko-KR");
return publicRecords
/*
정적 자료에는 축이 없다 — 사람이 Studio 에서 거는 값이라 픽스처가 지어낼 수 없다. 축으로
걸러 달라는 요청은 아무것도 고르지 않는 것으로 답한다. 없는 것을 있는 척하면 이 어댑터로
그린 화면이 서버로 바꿨을 때 달라진다.
*/
.filter(() => !filters.variant)
.filter((record) => !filters.kind || record.kind === filters.kind)
.filter(
(record) =>
!hasTopicFilter ||
record.topicSlug.toLocaleLowerCase("ko-KR") === requestedTopic ||
record.topic.toLocaleLowerCase("ko-KR") === requestedTopic,
)
.filter(
(record) =>
!hasProjectFilter ||
record.projectSlug.toLocaleLowerCase("ko-KR") === requestedProject ||
record.projectTitle.toLocaleLowerCase("ko-KR") === requestedProject,
)
.filter(
(record) =>
!filters.openQuestionsOnly ||
(record.kind === "QUESTION" &&
record.questionStatus !== "RESOLVED" &&
record.questionStatus !== "ARCHIVED"),
)
.sort(comparePublishedAt);
}
export function getRecord<K extends RecordKind>(
kind: K,
slug: string,
): Extract<PublicRecord, { kind: K }> | undefined {
return publicRecords.find(
(record) => record.kind === kind && record.slug === slug,
) as Extract<PublicRecord, { kind: K }> | undefined;
}
export function getProject(slug: string): Project | undefined {
return projects.find((project) => project.slug === slug);
}
export function getRelease(version: string): Release | undefined {
return releases.find((release) => release.version === version);
}
export function getProjectRecords(projectSlug: string): PublicRecord[] {
if (!getProject(projectSlug)) return [];
return listRecords({ project: projectSlug });
}
export function getProjectDecisions(projectSlug: string): ProjectDecision[] {
return [...(getProject(projectSlug)?.decisions ?? [])];
}
export function getProjectActivity(projectSlug: string): ProjectActivity[] {
return [...(getProject(projectSlug)?.activity ?? [])];
}
/**
* 정적 카탈로그에는 주제 테이블이 없다 — 기록마다 붙은 주제 이름이 있을 뿐이다. 그것을 모아
* 세면 백엔드의 `listPublicTopics` 와 같은 모양이 되고, 이 어댑터의 목적(백엔드 없이 화면을
* 그린다)에도 맞는다.
*/
export function listTopics(): PublicTopic[] {
const counts = new Map<string, PublicTopic>();
for (const record of listRecords()) {
if (!record.topic) continue;
const existing = counts.get(record.topicSlug);
if (existing) {
counts.set(record.topicSlug, { ...existing, recordCount: existing.recordCount + 1 });
continue;
}
/*
정적 자료에는 논지도 축도 없다 — 사람이 Studio 에서 쓰는 글이라 픽스처가 지어낼 수 없다.
화면은 비면 그 줄을 그리지 않는다.
*/
counts.set(record.topicSlug, {
name: record.topic,
slug: record.topicSlug,
thesis: "",
description: "",
variantLabel: "",
variantCount: 0,
recordCount: 1,
});
}
return [...counts.values()]
.sort((left, right) => right.recordCount - left.recordCount || (left.name < right.name ? -1 : 1))
.map((entry) => Object.freeze(entry));
}
/**
* 픽스처판 주제 한 편.
*
* <p>정적 카탈로그에는 축(variant)도 논지(thesis)도 없다 — 사람이 쓰는 글이라 픽스처가 지어낼
* 수 없다. 그래서 축은 비고, 기록만 종류별로 모은다. 화면은 축이 비면 축을 그리지 않는다.
*/
export function getTopicDetail(slug: string): PublicTopicDetail | undefined {
const records = listRecords().filter((record) => record.topicSlug === slug);
if (records.length === 0) return undefined;
const pick = (kind: RecordKind, label: string) =>
Object.freeze(
records
.filter((record) => record.kind === kind)
.map((record) =>
Object.freeze({
label,
title: record.title,
path: record.path,
summary: record.summary,
note: "",
priority: 0,
}),
),
);
const projects = new Map(
records
.filter((record) => record.projectSlug)
.map((record) => [
record.projectSlug,
Object.freeze({
label: "프로젝트",
title: record.projectTitle,
path: `/projects/${record.projectSlug}`,
summary: "",
note: "",
priority: 0,
}),
]),
);
return Object.freeze({
name: records[0]!.topic,
slug,
description: "",
thesis: "",
variantLabel: "",
variants: Object.freeze([]),
featuredCases: pick("CASE", "검증 기록"),
activeQuestions: pick("QUESTION", "열린 질문"),
relatedProjects: Object.freeze([...projects.values()]),
});
}
/**
* 픽스처판 "최근 기록". HTTP 어댑터가 서버에서 읽어 오는 것과 같은 의미를 픽스처에서 만든다 —
* 프로젝트 활동과 릴리스가 원천이다.
*/
export function getLatestEntries(): LatestRecordEntry[] {
const recordByPath = new Map(publicRecords.map((record) => [record.path, record]));
const activities = projects.flatMap((project) =>
project.activity.map((activity) => {
const record = recordByPath.get(activity.recordPath ?? activity.path);
// 기록을 공개한 활동인가. 종류 이름이 아니라 접미사로 가른다 — 종류가 늘어도 그대로다.
const published = activity.type.endsWith("_PUBLISHED") && record;
return {
id: activity.id,
entryType: (published ? record.kind : "PROJECT_ACTIVITY") as LatestRecordEntry["entryType"],
title: published ? record.title : activity.title,
summary: activity.summary,
path: activity.path,
publishedAt: activity.dateTime,
topic: record?.topic ?? project.topics[0]?.name ?? "",
project: project.title,
};
}),
);
/*
릴리스는 넣지 않는다. 이 목록은 서버의 `latestEntries` 와 같은 의미여야 하고, 그쪽은 공개
투영에서 고르므로 릴리스가 없다 — 릴리스는 Publication 파이프라인을 거치지 않는다. 홈 화면이
릴리스를 따로 읽어 합치므로, 여기서도 넣으면 같은 릴리스가 두 번 나온다.
*/
return [...activities].sort((left, right) =>
right.publishedAt.localeCompare(left.publishedAt),
);
}
export function getHomeFocusItems(): HomeFocusItem[] {
const project = getProject("backend-skeleton");
const question = getRecord("QUESTION", "validate-edge-token-again");
const decision = getProjectDecisions("backend-skeleton").find(
(item) => item.id === "storage-port-unification",
);
if (!project || !question || !decision) {
throw new Error("Missing canonical entity required for the public home focus");
}
return [
{
key: "current",
label: "현재 작업",
title: project.title,
summary: project.summary,
details: [
{ label: "단계", value: projectStageLabel(project.stage) },
{ label: "현재 목표", value: project.currentGoal },
{ label: "다음 작업", value: project.nextStep },
],
targetPath: `/projects/${project.slug}`,
},
{
key: "question",
label: "열린 질문",
title: question.title,
summary: question.summary,
details: [
{ label: "확인한 사실", value: question.facts[0] ?? "" },
{ label: "남은 미지수", value: question.unknowns[0] ?? "" },
{ label: "다음 검증", value: question.nextValidation },
],
targetPath: question.path,
},
{
key: "decision",
label: "최근 결정",
title: decision.statement,
summary: decision.rationale,
details: [
{ label: "영향", value: decision.consequences[0] ?? "" },
{ label: "근거", value: decision.evidence[0]?.title ?? "" },
],
targetPath: `/projects/${project.slug}/decisions#${decision.id}`,
},
];
}
function recordSearchEntity(record: PublicRecord): SearchablePublicEntity {
return {
contentType: record.kind,
title: record.title,
summary: record.summary,
path: record.path,
topic: record.topic,
project: record.projectTitle,
publishedAt: record.publishedAt,
};
}
function projectSearchEntity(project: Project): SearchablePublicEntity {
return {
contentType: "PROJECT",
title: project.title,
summary: project.summary,
path: `/projects/${project.slug}`,
// 검색 항목의 주제는 이름만 쓴다 — 검색어와 맞춰 보는 자리다.
topics: project.topics.map((topic) => topic.name),
project: project.title,
};
}
function releaseSearchEntity(release: Release): SearchablePublicEntity {
return {
contentType: "RELEASE",
title: release.title,
summary: release.summary,
path: release.path,
topic: "TechLog",
project: "TechLog",
publishedAt: release.publishedAt,
};
}
export function listCatalog(): SearchablePublicEntity[] {
return [
...publicRecords.map(recordSearchEntity),
...projects.map(projectSearchEntity),
...releases.map(releaseSearchEntity),
];
}
export function searchPublicContent(query: string): SearchablePublicEntity[] {
const normalizedQuery = query.trim().toLocaleLowerCase("ko-KR");
const entities = listCatalog();
if (!normalizedQuery) return entities;
return entities.filter((entity) =>
[
entity.title,
entity.summary,
entity.topic,
entity.project,
...(entity.topics ?? []),
]
.filter((value): value is string => Boolean(value))
.some((value) =>
value.toLocaleLowerCase("ko-KR").includes(normalizedQuery),
),
);
}
/**
* The MOCK source. The functions above stay synchronous — they filter arrays
* that are already in the bundle, and making them async would only add a
* microtask to every fixture test — so the port's async shape is applied here,
* at the adapter boundary, rather than pushed into the query implementations.
*
* `async` rather than `Promise.resolve(...)` so a throw from one of these
* becomes a rejected promise like the HTTP adapter's would, instead of
* escaping synchronously past the caller's await.
*/
export const publicContentQueries = Object.freeze({
async listRecords(filters?: RecordFilters) {
return listRecords(filters);
},
async getRecord<K extends RecordKind>(kind: K, slug: string) {
return getRecord(kind, slug);
},
async getProject(slug: string) {
return getProject(slug);
},
async getRelease(version: string) {
return getRelease(version);
},
async getProjectRecords(projectSlug: string) {
return getProjectRecords(projectSlug);
},
async getProjectDecisions(projectSlug: string) {
return getProjectDecisions(projectSlug);
},
async getProjectActivity(projectSlug: string) {
return getProjectActivity(projectSlug);
},
/* 정적 카탈로그에는 프로필이 없다. 빈 목록이면 화면이 그 구역을 그리지 않는다. */
async listContacts() {
return [];
},
async listTopics() {
return listTopics();
},
async getTopicDetail(slug: string) {
return getTopicDetail(slug);
},
async getHome() {
return Object.freeze({
focusItems: Object.freeze(getHomeFocusItems()),
latestEntries: Object.freeze(getLatestEntries()),
});
},
async listProjects() {
return projects.map((project) =>
Object.freeze({
slug: project.slug,
title: project.title,
summary: project.summary,
path: `/projects/${project.slug}`,
}),
);
},
async listReleases() {
return releases.map((release) =>
Object.freeze({
version: release.version,
title: release.title,
summary: release.summary,
path: release.path,
}),
);
},
async listCatalog() {
return listCatalog();
},
async getLatestEntries() {
return getLatestEntries();
},
async getHomeFocusItems() {
return getHomeFocusItems();
},
async searchPublicContent(query: string) {
return searchPublicContent(query);
},
}) satisfies PublicContentQueries;