jsperf-img-svc
Version:
A simple micro service for loading jsperf result charts as a static image
62 lines (57 loc) • 1.71 kB
JavaScript
const
_ = require('lodash'),
Promise = require('bluebird'),
FeedParser = require('feedparser'),
request = require('request'),
highland = require('highland'),
moment = require('moment'),
MD5 = require('crypto-js/md5'),
cache = require('./cache'),
shared = require('./shared'),
config = require('./config');
module.exports = class TestCase {
constructor(slug, rev){
this.slug = slug;
this.feed = `${config.remoteBase}/${slug}.atom`;
this.rev = (rev == 'latest' ? rev : (_.parseInt(_.isUndefined(rev) ? 0 : rev) || 1));
this.feedKey = `feed:${MD5(this.feed).toString()}@${this.rev}`;
}
fetch(){
const client = cache.getClient();
return cache
.expired(client, this.feedKey)
.then(() => {
return cache
.read(client, this.feedKey)
.then(json => JSON.parse(json));
})
.catch(() => {
return new Promise((resolve, reject) => {
return request
.get(this.feed)
.pipe(new FeedParser({addmeta: false}))
.on('error', reject)
.pipe(highland())
.flatten()
.through(shared.streamToPromise)
.then((feedArray) => {
let index = (this.rev == 'latest' ? feedArray.length : this.rev) - 1;
return feedArray[index];
})
.then(resolve);
})
})
.then((revision) => {
this.guid = revision.guid;
this.link = revision.link;
this.date = moment(revision.date).toISOString();
let imageId = MD5(`${this.guid}${this.date}`).toString();
this.image = `/cache/image/${imageId}`;
this.imageKey = `image:${imageId}`;
// don't wait for cache write to complete
cache.write(client, this.feedKey, JSON.stringify(revision), config.feedTTL);
})
.return(this);
}
};
;