extract the parser api to a base class
[rss-reader.git] / src / parsers / rss.ts
1 import Parser from 'rss-parser';
2 import {Feed, BaseParser} from './base';
3
4 function timestamp(str: string): number {
5   const date = +(new Date(str));
6   return Math.floor(date / 1000);
7 }
8
9 function reasonable(dateStr: string): string {
10   const date = new Date(dateStr);
11   const month = date.getMonth() < 10 ? `0${date.getMonth()}` : date.getMonth();
12   const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
13   return `${date.getFullYear()}-${month}-${day}`;
14 }
15
16 export class RSSParser extends BaseParser {
17   parser: Parser;
18   constructor() {
19     super();
20     this.parser = new Parser;
21   }
22
23   async parse(url: string): Promise<Feed> {
24     const feed = await this.parser.parseURL(url);
25
26     return {
27       title: feed.title || 'Unknown',
28       link: feed.link || 'Unknown',
29       items: feed.items.map(i => {
30         const content = i.content ? i.content : i.description;
31         const title = i.title ? i.title : `Posted on ${reasonable(i.pubDate || (new Date().toString()))}`;
32         return {
33           title: title || 'Unknown',
34           link: i.link || 'Unknown',
35           guid: i.guid || 'Uknown',
36           content: content || 'Unknown',
37           pubDate: (timestamp(i.pubDate || (new Date().toString())))
38         }
39       })
40     }
41   }
42 }