1
0
mirror of https://github.com/trambarhq/relaks-wordpress-example.git synced 2025-10-04 19:21:38 +02:00
Files
relaks-wordpress-example/server/json-retriever.js
Chung Leong c5fd724e2f Reworked code to allow use of basePath other than / (issue #20).
Throwing error properly in JSON retrieval code (issue #44).
2019-01-30 21:57:52 +01:00

49 lines
1.3 KiB
JavaScript

const CrossFetch = require('cross-fetch');
const WORDPRESS_HOST = process.env.WORDPRESS_HOST;
async function fetch(path) {
console.log(`Retrieving data: ${path}`);
let url = `${WORDPRESS_HOST}${path}`;
let res = await CrossFetch(url);
let resText = await res.text();
let object;
try {
object = JSON.parse(resText);
} catch (err) {
// remove any error msg that got dumped into the output stream
resText = resText.replace(/^[^\{\[]+/, '');
object = JSON.parse(resText);
}
if (res.status >= 400) {
let msg = (object && object.message) ? object.message : 'Unknown error';
let err = new Error(msg);
err.status = res.status;
throw err;
}
let total = parseInt(res.headers.get('X-WP-Total'));
removeSuperfluousProps(path, object);
let text = JSON.stringify(object);
return { path, text, total };
}
function removeSuperfluousProps(path, object) {
if (object instanceof Array) {
let objects = object;
for (let object of objects) {
removeSuperfluousProps(path, object);
}
} else if (object instanceof Object) {
delete object._links;
if (path === '/wp-json/') {
delete object.routes;
} else {
delete object.guid;
}
}
}
module.exports = {
fetch,
};