Skip to content

Instantly share code, notes, and snippets.

@asherkin
Created November 3, 2017 20:58
Show Gist options
  • Save asherkin/ac5a9e97799a0a3ad3a7c5dd464f01be to your computer and use it in GitHub Desktop.
Save asherkin/ac5a9e97799a0a3ad3a7c5dd464f01be to your computer and use it in GitHub Desktop.
'use strict';
process.env.TZ = 'America/New_York';
const https = require('https');
const xml2js = require('xml2js');
const sourceUrl = 'https://forums.alliedmods.net/external.php?type=xml&forumids=108&count=5';
function formatTimestamp(date, time) {
date = date.match(/^(\d{2})-(\d{2})-(\d{4})$/);
time = time.match(/^(\d{2}):(\d{2})$/);
const d = new Date(date[3], date[1] - 1, date[2], time[1], time[2]);
return d.toISOString();
}
function parseTitle(title, author) {
return title
.replace(/\([^)]*\)/g, '')
.replace(/\[[^\]]*\]/g, '')
.replace(/\{[^}]*\}/g, '')
.replace(/([^A-Za-z0-9\.\$])|([A-Z])(?=[A-Z][a-z])|([^\-\$\.0-9])(?=\$?[0-9]+(?:\.[0-9]+)?)|([0-9])(?=[^\.0-9])|([a-z])(?=[A-Z])/g, '$2$3$4$5 ')
.replace(/\s+/g, ' ')
.trim() + ' was released by ' + author;
}
exports.handler = (event, context, callback) => {
console.log('Received event:', JSON.stringify(event, null, 2));
const req = https.request(sourceUrl, (res) => {
if (res.statusCode != 200) {
callback(new Error('Request failed: ' + res.statusCode));
return;
}
console.log('Forum response headers:', JSON.stringify(res.headers, null, 2));
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
xml2js.parseString(data, { trim: true, explicitRoot: false, async: true }, (err, data) => {
if (err) {
callback(err);
return;
}
console.log('Forum response:', JSON.stringify(data, null, 2));
data = data.thread.map((thread) => ({
uid: 'urn:alliedmodders:threadid:' + thread.$.id,
updateDate: formatTimestamp(thread.date[0], thread.time[0]),
titleText: thread.title[0],
mainText: parseTitle(thread.title[0], thread.author[0]),
redirectionUrl: data.url + 'showthread.php?t=' + thread.$.id,
}));
console.log('Response:', JSON.stringify(data, null, 2));
callback(null, {
statusCode: 200,
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
});
});
});
});
req.on('error', (err) => {
callback(err);
});
req.end();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment