UNPKG

1.45 kBPlain TextView Raw
1import { htmlToText } from "html-to-text";
2import { Item } from "./item";
3import { ItemType } from "./item-type";
4import { RawItem } from "./raw-item";
5import { unixToIsoString } from "./unix-to-iso-string";
6
7/**
8 * `normalizeRawItem` transforms a `RawItem` into an `Item`.
9 */
10export function normalizeRawItem({ rawItem }: { rawItem: RawItem }): Item {
11 // Make `type` not null
12 const type: ItemType = rawItem.type ?? "unknown";
13
14 // Convert Unix time in seconds to UTC timestamp
15 const timestamp = rawItem.time
16 ? unixToIsoString({ time: rawItem.time })
17 : undefined;
18
19 // Make `deleted` and `dead` not null
20 const deleted = rawItem.deleted ?? false;
21 const dead = rawItem.dead ?? false;
22
23 // Convert `title` and `text` from HTML to plain text;
24 // for example, see from API https://hacker-news.firebaseio.com/v0/item/24753101.json
25 // and rendered https://news.ycombinator.com/item?id=24753101
26 const title = rawItem.title
27 ? htmlToText(rawItem.title, { wordwrap: false })
28 : undefined;
29 const text = rawItem.text
30 ? htmlToText(rawItem.text, { wordwrap: false })
31 : undefined;
32
33 return {
34 id: rawItem.id,
35 type,
36 author: rawItem.by,
37 title,
38 url: rawItem.url,
39 text,
40 timestamp,
41 score: rawItem.score,
42 numChildren: rawItem.descendants,
43 deleted,
44 dead,
45 parentId: rawItem.parent,
46 childrenIds: rawItem.kids,
47 pollId: rawItem.poll,
48 pollOptionsIds: rawItem.parts,
49 };
50}