diff --git a/src/blog/utils/articles.ts b/src/blog/utils/articles.ts new file mode 100644 index 0000000..2a034d2 --- /dev/null +++ b/src/blog/utils/articles.ts @@ -0,0 +1,76 @@ +import { + ArticleModel, + ArticleRepoModel +} from "../types/models"; + +// List helpers +export function createInList(list: ArticleModel[], a: ArticleModel) { + return [a, ...list]; +} + +export function readInList(list: ArticleModel[], index: number) { + if (index < 0 || index >= list.length) { + // Soft fallback + return undefined; + } + return list[index]; +} + +export function updateInList(list: ArticleModel[], a: ArticleModel) { + return list.map(x => (x._id === a._id ? a : x)); +} + +export function deleteInList(list: ArticleModel[], id: string) { + return list.filter(x => x._id !== id); +} + +// Map helpers +export function createById( + map: Record, + a: ArticleModel +) { + if (!a._id) { + // Soft mode: ignore create, return unchanged + return map; + } + + if (map[a._id]) { + // Soft mode: do not replace existing + return map; + } + + return { ...map, [a._id]: a }; +} + +export function readById( + map: Record, + id: string +) { + if (!id) return undefined; + return map[id]; +} + +export function updateById( + map: Record, + a: ArticleModel +) { + if (!a._id) { + // Cannot update without ID + return map; + } + + if (!map[a._id]) { + // ID does not exist → soft mode: do nothing + return map; + } + + return { ...map, [a._id]: a }; +} + +export function deleteById( + map: Record, + id: string +) { + const { [id]: _, ...rest } = map; + return rest; +}