combine.fm/routes/share.js

46 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-08-20 23:22:57 +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-08-20 23:22:57 +01:00
function formatAndSort(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-08-20 23:22:57 +01:00
export default function* (serviceId, type, itemId, format, next) {
2015-06-03 21:45:54 -07:00
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-08-20 23:22:57 +01:00
const doc = yield this.db.matches.findOne({_id: serviceId + '$$' + itemId});
2015-06-03 21:45:54 -07:00
this.assert(doc, 404, 'Not Found');
2015-01-06 12:58:57 +00:00
2015-08-20 23:22:57 +01:00
const shares = formatAndSort(doc.services, serviceId);
2015-06-03 21:45:54 -07:00
if (format === 'json') {
this.body = {shares: shares};
} else {
2015-08-20 23:22:57 +01:00
const Handler = yield createHandler(routes, this.request.url);
2015-06-03 21:45:54 -07:00
2015-08-20 23:22:57 +01:00
const App = React.createFactory(Handler);
2015-06-03 21:45:54 -07:00
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;
}
};