1 | ;
|
2 |
|
3 | const { config } = require('./package.json');
|
4 | const WordPressClient = require('wp-api-client');
|
5 | const client = new WordPressClient(config.baseUrl);
|
6 |
|
7 | /**
|
8 | * Retrieve contents of [haiku.ist/about](https://haiku.ist/about/) page.
|
9 | * @return {Promise<Page>} About page.
|
10 | */
|
11 | const about = () => client.fetchPage(config.aboutPage);
|
12 | /**
|
13 | * Get total number of haikus.
|
14 | * @return {Promise<Number>} Total number of haikus available.
|
15 | */
|
16 | const count = () => client.countPosts({ categories: config.haikus });
|
17 | /**
|
18 | * Retrieve multiple haikus from [haiku.ist](https://haiku.ist) archive.
|
19 | * @param {Object} options WordPress REST API `/posts` endpoint
|
20 | * [arguments](https://developer.wordpress.org/rest-api/reference/posts/#arguments).
|
21 | * @param {Number} [options.pageSize=10] Maximum number of items to be returned in result set.
|
22 | * @return {Promise<Response<Post>>} Paginated listing of haiku posts.
|
23 | */
|
24 | const fetchPosts = options => client.fetchPosts({ ...options, categories: config.haikus });
|
25 |
|
26 | module.exports = {
|
27 | about,
|
28 | count,
|
29 | fetchLatest,
|
30 | fetchPosts,
|
31 | fetchRandom
|
32 | };
|
33 |
|
34 | /**
|
35 | * Fetch latest haiku.
|
36 | * @return {Promise<Post>} Latest post containing haiku.
|
37 | */
|
38 | async function fetchLatest() {
|
39 | const { items: posts } = await fetchPosts({ pageSize: 1 });
|
40 | return posts[0];
|
41 | }
|
42 |
|
43 | /**
|
44 | * Fetch random haiku from [haiku.ist](https://haiku.ist) archive.
|
45 | * @return {Promise<Post>} Random post containing haiku.
|
46 | */
|
47 | async function fetchRandom() {
|
48 | const max = await count();
|
49 | const offset = random(max);
|
50 | const { items: posts } = await fetchPosts({ offset });
|
51 | return posts[0];
|
52 | }
|
53 |
|
54 | function random(max) {
|
55 | return Math.floor(Math.random() * Math.floor(max));
|
56 | }
|
57 |
|
58 | /**
|
59 | * WordPress API client `Page` response type.
|
60 | * @typedef {WordPressClient.Page} Page
|
61 | * @see https://www.npmjs.com/package/wp-api-client#page
|
62 | */
|
63 | /**
|
64 | * WordPress API client `Post` response type.
|
65 | * @typedef {WordPressClient.Post} Post
|
66 | * @see https://www.npmjs.com/package/wp-api-client#post
|
67 | */
|
68 |
|
69 | /**
|
70 | * WordPress API client response type used for paginated responses.
|
71 | * @typedef {WordPressClient.Response<T>} Response @template T
|
72 | * @see https://www.npmjs.com/package/wp-api-client#response
|
73 | */
|