Last active
October 7, 2018 18:12
-
-
Save vladimyr/2f30b29a70434bc18a51958737ff71c3 to your computer and use it in GitHub Desktop.
haiku.ist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const minidom = require('minidom'); | |
const r = require('got'); | |
const urlJoin = require('url-join'); | |
const API_URL = 'https://haiku.ist/wp-json/wp/v2/'; | |
module.exports = { | |
count, | |
fetchLatest, | |
fetchPosts, | |
fetchRandom | |
}; | |
async function fetchLatest() { | |
const { posts } = await fetchPosts({ pageSize: 1 }); | |
return posts[0]; | |
} | |
async function fetchRandom() { | |
const max = await count(); | |
const offset = random(max); | |
const { posts } = await fetchPosts({ offset }); | |
return posts[0]; | |
} | |
async function count() { | |
const url = urlJoin(API_URL, '/posts'); | |
const { headers } = await r.head(url); | |
return parseInt(headers['x-wp-total'], 10); | |
} | |
async function fetchPosts({ pageSize = 10, offset = 0 } = {}) { | |
const query = `per_page=${pageSize}&offset=${offset}`; | |
const url = urlJoin(API_URL, `/posts?${query}`); | |
const { headers, body = [] } = await r.get(url, { json: true }); | |
const total = parseInt(headers['x-wp-total'], 10); | |
const totalPages = parseInt(headers['x-wp-totalpages'], 10); | |
const posts = body.map(it => ({ | |
id: it.id, | |
createdAt: it.date, | |
modifiedAt: it.date, | |
link: it.link, | |
title: it.title.rendered, | |
content: getText(it.content.rendered) | |
})); | |
return { total, totalPages, pageSize, posts }; | |
} | |
function getText(html) { | |
const doc = minidom(html); | |
const body = doc.getElementsByTagName('body').item(0); | |
return body.textContent.trim(); | |
} | |
function random(max) { | |
return Math.floor(Math.random() * Math.floor(max)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment