diff --git a/src/lib/article.js b/src/lib/article.js new file mode 100644 index 0000000..bca7b55 --- /dev/null +++ b/src/lib/article.js @@ -0,0 +1,37 @@ +"use strict"; + +function normalizeWhitespace(text) { + return text.replace(/\s+/g, " ").trim(); +} + +function extractArticleFromParent(parentPost) { + if (!parentPost || typeof parentPost !== "object") { + return { ok: false, error: "parent_post_missing" }; + } + + const article = parentPost.article; + if (!article || typeof article.body !== "string") { + return { ok: false, error: "not_article" }; + } + + const rawBody = normalizeWhitespace(article.body); + if (!rawBody) { + return { ok: false, error: "empty_article" }; + } + + return { + ok: true, + article: { + xArticleId: article.id || null, + parentPostId: parentPost.id, + authorId: parentPost.authorId || null, + title: article.title || "Untitled", + content: rawBody, + charCount: rawBody.length, + }, + }; +} + +module.exports = { + extractArticleFromParent, +}; diff --git a/test/article.test.js b/test/article.test.js new file mode 100644 index 0000000..01fa0ee --- /dev/null +++ b/test/article.test.js @@ -0,0 +1,40 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { extractArticleFromParent } = require("../src/lib/article"); + +test("returns not_article when parent has no article payload", () => { + const result = extractArticleFromParent({ id: "p1", text: "hello" }); + assert.equal(result.ok, false); + assert.equal(result.error, "not_article"); +}); + +test("extracts article body and char count", () => { + const result = extractArticleFromParent({ + id: "p1", + authorId: "author-1", + article: { + id: "art-1", + title: "My Article", + body: " Hello world\n\nfrom X article. ", + }, + }); + + assert.equal(result.ok, true); + assert.equal(result.article.title, "My Article"); + assert.equal(result.article.content, "Hello world from X article."); + assert.equal(result.article.charCount, "Hello world from X article.".length); +}); + +test("returns empty_article when body is blank", () => { + const result = extractArticleFromParent({ + id: "p1", + article: { + body: " \n\n\t", + }, + }); + + assert.equal(result.ok, false); + assert.equal(result.error, "empty_article"); +});