1 | 'use strict';
|
2 |
|
3 | const debug = require('debug')('http');
|
4 | const html2text = require('html2plaintext');
|
5 | const r = require('got');
|
6 | const urlJoin = require('url-join');
|
7 |
|
8 | const API_URL = 'https://haiku.ist/wp-json/wp/v2/';
|
9 | const ABOUT = 10;
|
10 | const HAIKU = 2;
|
11 |
|
12 | const normalize = url => url.replace(/\/$/, '');
|
13 |
|
14 | module.exports = {
|
15 | about,
|
16 | count,
|
17 | fetchLatest,
|
18 | fetchPosts,
|
19 | fetchRandom
|
20 | };
|
21 |
|
22 | async function fetchLatest() {
|
23 | const { posts } = await fetchPosts({ pageSize: 1 });
|
24 | return posts[0];
|
25 | }
|
26 |
|
27 | async function fetchRandom() {
|
28 | const max = await count();
|
29 | const offset = random(max);
|
30 | const { posts } = await fetchPosts({ offset });
|
31 | return posts[0];
|
32 | }
|
33 |
|
34 | async function about() {
|
35 | const url = urlJoin(API_URL, `/pages/${ABOUT}`);
|
36 | debug('url:', url);
|
37 | const { body: page = {} } = await r.get(url, { json: true });
|
38 | return {
|
39 | createdAt: page.date,
|
40 | modifiedAt: page.modified,
|
41 | link: normalize(page.link),
|
42 | ...parsePost(page)
|
43 | };
|
44 | }
|
45 |
|
46 | async function count() {
|
47 | const query = `categories=${HAIKU}`;
|
48 | const url = urlJoin(API_URL, `/posts?${query}`);
|
49 | debug('url:', url);
|
50 | const { headers } = await r.head(url);
|
51 | return parseInt(headers['x-wp-total'], 10);
|
52 | }
|
53 |
|
54 | async function fetchPosts({ pageSize = 10, offset = 0 } = {}) {
|
55 | const query = `categories=${HAIKU}&per_page=${pageSize}&offset=${offset}`;
|
56 | const url = urlJoin(API_URL, `/posts?${query}`);
|
57 | debug('url:', url);
|
58 | const { headers, body = [] } = await r.get(url, { json: true });
|
59 | const total = parseInt(headers['x-wp-total'], 10);
|
60 | const totalPages = parseInt(headers['x-wp-totalpages'], 10);
|
61 | const posts = body.map(it => ({
|
62 | id: it.id,
|
63 | createdAt: it.date,
|
64 | modifiedAt: it.modified,
|
65 | link: normalize(it.link),
|
66 | ...parsePost(it)
|
67 | }));
|
68 | return { total, totalPages, pageSize, posts };
|
69 | }
|
70 |
|
71 | function parsePost({ title, content } = {}) {
|
72 | title = html2text(title.rendered);
|
73 | content = html2text(content.rendered);
|
74 | return { title, content };
|
75 | }
|
76 |
|
77 | function random(max) {
|
78 | return Math.floor(Math.random() * Math.floor(max));
|
79 | }
|