UNPKG

2.02 kBJavaScriptView Raw
1'use strict';
2
3const debug = require('debug')('http');
4const html2text = require('html2plaintext');
5const r = require('got');
6const urlJoin = require('url-join');
7
8const API_URL = 'https://haiku.ist/wp-json/wp/v2/';
9const ABOUT = 10;
10const HAIKU = 2;
11
12const normalize = url => url.replace(/\/$/, '');
13
14module.exports = {
15 about,
16 count,
17 fetchLatest,
18 fetchPosts,
19 fetchRandom
20};
21
22async function fetchLatest() {
23 const { posts } = await fetchPosts({ pageSize: 1 });
24 return posts[0];
25}
26
27async function fetchRandom() {
28 const max = await count();
29 const offset = random(max);
30 const { posts } = await fetchPosts({ offset });
31 return posts[0];
32}
33
34async 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
46async 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
54async 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
71function parsePost({ title, content } = {}) {
72 title = html2text(title.rendered);
73 content = html2text(content.rendered);
74 return { title, content };
75}
76
77function random(max) {
78 return Math.floor(Math.random() * Math.floor(max));
79}