Skip to content

Instantly share code, notes, and snippets.

@roxeteer
Created November 25, 2018 09:22
Show Gist options
  • Save roxeteer/42714e7c09bde3357be071d72863e8ba to your computer and use it in GitHub Desktop.
Save roxeteer/42714e7c09bde3357be071d72863e8ba to your computer and use it in GitHub Desktop.
const arc = require('@architect/functions');
const { DateTime } = require('luxon');
const { createPost } = require('@architect/shared/ghost_post');
async function route(req, res) {
const { GHOST_NAME } = process.env;
let post
try {
console.log('Received tweet', req.body);
// Message
const sections = [];
const cards = [];
// Body text
cards.push([
'markdown',
{ markdown: req.body.text }
]);
sections.push([10, cards.length - 1]);
// Twitter link
cards.push([
'html',
{ html: `<p class="twitter-link"><a href="${req.body.url}" target="_blank" rel="noopener"><span>Open in Twitter</span></a></p>` }
]);
sections.push([10, cards.length - 1]);
const mobiledoc = {
version: '0.3.1',
markups: [],
atoms: [],
cards,
sections
};
// Create time
// Twitter gives creation time in format `Thu Nov 22 05:37:30 +0000 2018`
const created = DateTime
.fromFormat(req.body.created, 'ccc LLL dd HH:mm:ss ZZZ yyyy')
.setZone('Europe/Helsinki'); // Change this to your local timezone
const formatted = created.toFormat('d.M.yyyy H:mm'); // Change this to the format of your choice
const slugFormatted = created.toFormat('dd-MM-yyyy-HH-mm');
const createdISO = created.toISO();
post = await createPost({
mobiledoc: JSON.stringify(mobiledoc),
title: `Twitter ${formatted}`,
slug: `twitter-${slugFormatted}`,
created_at: createdISO,
// Publish immediately, remove these if you want to create a draft
published_at: createdISO,
status: 'published',
visibility: 'public'
});
} catch (e) {
console.error(e.body || e);
let errorResult = e.statusMessage || e.message;
if (e.body && e.body.errors) {
errorResult = e.body.errors.map((err) => `${err.errorType}: ${err.message}`).join('\n');
}
return res({
status: 500,
body: errorResult
});
}
// Returns the post in JSON, not really required
return res({
type: 'application/json; charset=utf8',
body: JSON.stringify(post)
});
}
exports.handler = arc.http(route);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment