Skip to content

Instantly share code, notes, and snippets.

@aaronmfparr
Created June 24, 2018 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aaronmfparr/ceca24cf18e1f71ad907d4763414f3dc to your computer and use it in GitHub Desktop.
Save aaronmfparr/ceca24cf18e1f71ad907d4763414f3dc to your computer and use it in GitHub Desktop.
A node script for making get requests of a Ghost blog's public API. Contains a function and configuration for a single blog.
// -----------------------------------------------------------------------------
// ghost.js
// Usage: node
// Send a get request to a ghost blog and return the response
// Ghost API: https://api.ghost.org/
// -----------------------------------------------------------------------------
//
// 'config' is not strictly necessary, as it is simply used to hold constants
const config = require('./config');
// require http or https in the config and export it
// or require one or the other here
const https = config.PROTOCOL;
// global constants for Ghost's Public API
const BLOG_DOMAIN = config.BLOG_DOMAIN;
const PUBLIC_URL = BLOG_DOMAIN + '/ghost/api/v0.1';
const CLIENT_ID = 'ghost-frontend';
const CLIENT_SECRET = config.BLOG_CLIENT_SECRET;
/**
* Make a GET request of Ghost's public API
* @return {promise} - which resolves into the response
*
* @param {string} endpoint : see https://api.ghost.org/docs/posts
* @param {object} params : value depends on the endpoint used. see docs.
*/
function getFromPublicAPI (endpoint = '', params = {})
{
if (endpoint === '') { return Promise.resolve(''); }
// merge user, pass, and params into a string
let paramString = 'client_id=' + CLIENT_ID + '&client_secret=' + CLIENT_SECRET +
'&' +
Object.keys(params).map(
(k) => encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
).join('&');
return new Promise((resolve, reject) =>
{
https.get(
PUBLIC_URL + '/' + endpoint + '/?' + paramString,
(resp) =>
{
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => { data += chunk; });
// The whole response has been received. Do something with it
resp.on('end', () => { resolve(JSON.parse(data)); });
}
).on('error', (err) => { reject(err); });
});
}
/**
* Not implemented yet
* I am unconvinced that this needs to be a class
* I include both here in case I wish to go this route some day
*/
// class Ghost
// {
// constructor (endpoint = '', params = {})
// {
// this.response = '';
// getFromPublicAPI(endpoint, params)
// .then((res) => { this.response = res; })
// .catch((err) => { console.log(err); });
// };
// }
module.exports = {
// Ghost: Ghost,
ghostAPI: getFromPublicAPI
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment