| 12 | // https://github.com/HackerNews/API |
| 13 | |
| 14 | export class HnDatabase { |
| 15 | db: DatabaseReference; |
| 16 | cache: HnCache; |
| 17 | |
| 18 | constructor(db: DatabaseReference, cache: HnCache) { |
| 19 | this.db = db; |
| 20 | this.cache = cache; |
| 21 | } |
| 22 | |
| 23 | async fetchNewsItem(id: number): Promise<NewsItemModel | void> { |
| 24 | logger('Fetching post:', `${HN_API_URL}/item/${id}.json`); |
| 25 | |
| 26 | return get(child(this.db, `item/${id}`)) |
| 27 | .then((postSnapshot) => { |
| 28 | const post = postSnapshot.val(); |
| 29 | |
| 30 | if (post !== null) { |
| 31 | const newsItem = new NewsItemModel({ |
| 32 | id: post.id, |
| 33 | creationTime: post.time * 1000, |
| 34 | commentCount: post.descendants, |
| 35 | comments: post.kids, |
| 36 | submitterId: post.by, |
| 37 | title: post.title, |
| 38 | upvoteCount: post.score, |
| 39 | url: post.url, |
| 40 | }); |
| 41 | |
| 42 | this.cache.setNewsItem(newsItem.id, newsItem); |
| 43 | logger('Created Post:', post.id); |
| 44 | |
| 45 | return newsItem; |
| 46 | } |
| 47 | |
| 48 | throw post; |
| 49 | }) |
| 50 | .catch((reason) => logger('Fetching post failed:', reason)); |
| 51 | } |
| 52 | |
| 53 | async fetchComment(id: number): Promise<CommentModel | void> { |
| 54 | logger('Fetching comment:', `${HN_API_URL}/item/${id}.json`); |
| 55 | |
| 56 | return get(child(this.db, `item/${id}`)) |
| 57 | .then((itemSnapshot) => { |
| 58 | const item = itemSnapshot.val(); |
| 59 | |
| 60 | if (item !== null && !item.deleted && !item.dead) { |
| 61 | const comment = new CommentModel({ |
| 62 | comments: item.kids, |
| 63 | creationTime: item.time * 1000, |
| 64 | id: item.id, |
| 65 | parent: item.parent, |
| 66 | submitterId: item.by, |
| 67 | text: item.text, |
| 68 | }); |
| 69 | |
| 70 | this.cache.setComment(comment.id, comment); |
| 71 | logger('Created Comment:', item.id); |
nothing calls this directly
no outgoing calls
no test coverage detected