Skip to content

Instantly share code, notes, and snippets.

@jweisman jweisman/index.js
Created Dec 17, 2016

Embed
What would you like to do?
Twitter Card Proxy
'use strict';
exports.handler = function(event, context) {
var agent = event.headers['User-Agent'] || 'None';
var path = event.path.substring(event.path.indexOf('http'));
if (agent.startsWith('Twitterbot')) {
var proxy = require('./proxy');
proxy(path, (err, status, headers, body) => {
var response = {
statusCode: status,
headers: {
"content-type": headers["content-type"],
"content-length": body.length
},
body: body
};
context.succeed(response);
});
} else {
// redirect
var response = {
statusCode: 301,
headers: {
"Location": path
}
};
context.succeed(response);
}
};
{
"dependencies": {
"cheerio": "^0.22.0",
"request": "^2.79.0"
}
}
'use strict';
var request = require('request');
module.exports = function(path, callback) {
request(path, (err, response, body) => {
var host = path.substring(0, path.indexOf('/',8));
let cheerio = require('cheerio'), $ = cheerio.load(body);
let title = $('article.blog h1').text();
let description = ($('article.blog header').next('p').text()) || '';
let image = ($('article.blog img').first().attr('src')) || '';
if (image != '') image = host + image;
var meta = `
<meta name="twitter:card" content="summary"/>
<meta name="twitter:site" content="@ExLibrisGroup"/>
<meta name="twitter:title" content="${title}"/>
<meta name="twitter:description" content="${description.substring(0,100)}"/>
<meta name="twitter:image" content="${image}"/>
`;
console.log('meta', meta);
$('head').append(meta);
callback(err, response.statusCode, response.headers, $.html());
});
}
'use strict';
var http = require('http');
const PORT=8080;
var server = http.createServer((req, resp) => {
var path = req.url.substring(req.url.indexOf('http'));
var agent = req.headers['user-agent'] || 'None';
if (agent.startsWith('Twitterbot')) {
var proxy = require('./proxy');
proxy(path, (err, status, headers, body) => {
resp.writeHead(status, headers);
resp.end(body);
});
} else {
// redirect
resp.writeHead(301, { "Location": path} );
resp.end();
}
});
server.listen(process.env.PORT || PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.