combine.fm/routes/share.js

47 lines
1.3 KiB
JavaScript
Raw Normal View History

2015-06-03 21:45:54 -07:00
import React from 'react';
import createHandler from '../lib/react-handler';
2015-06-15 02:34:39 +01:00
import {routes} from '../views/app';
2015-06-03 21:45:54 -07:00
import services from '../lib/services';
2014-12-15 12:49:17 +00:00
2015-06-03 21:45:54 -07:00
let formatAndSort = function(matches, serviceId) {
2015-05-17 19:10:30 +01:00
matches = Object.keys(matches).map(function (key) {return matches[key]; });
matches.sort(function(a, b) {
return a.id && !b.id;
2015-05-17 19:10:30 +01:00
}).sort(function(a) {
return a.service !== serviceId;
});
return matches;
2015-05-17 19:10:30 +01:00
};
2015-06-03 21:45:54 -07:00
module.exports = function* (serviceId, type, itemId, format, next) {
let matchedService;
2015-01-06 12:58:57 +00:00
services.some(function(service) {
2015-05-17 19:10:30 +01:00
matchedService = serviceId === service.id ? service : null;
2015-01-06 12:58:57 +00:00
return matchedService;
});
2014-12-05 17:40:07 +00:00
2015-06-03 21:45:54 -07:00
if (!matchedService || (type !== 'album' && type !== 'track')) {
return yield next;
2015-01-06 12:58:57 +00:00
}
2015-06-03 21:45:54 -07:00
let shares = [];
let doc = yield this.db.matches.findOne({_id: serviceId + '$$' + itemId});
this.assert(doc, 404, 'Not Found');
2015-01-06 12:58:57 +00:00
2015-06-03 21:45:54 -07:00
shares = formatAndSort(doc.services, serviceId);
if (format === 'json') {
this.body = {shares: shares};
} else {
let Handler = yield createHandler(routes, this.request.url);
let App = React.createFactory(Handler);
let content = React.renderToString(new App({shares: shares}));
content = content.replace('</body></html>', '<script>var shares = ' + JSON.stringify(shares) + '</script></body></html>');
this.body = '<!doctype html>\n' + content;
}
};