|
| 1 | +var cheerio = require('cheerio'), |
| 2 | + request = require('request'); |
| 3 | + |
| 4 | +var cache = require('./cache'), |
| 5 | + config = require('./config'); |
| 6 | + |
| 7 | +var problems = {}; |
| 8 | + |
| 9 | +problems.getAll = function(cb) { |
| 10 | + var items = cache.get('all'); |
| 11 | + if (items) return cb(null, items); |
| 12 | + |
| 13 | + // cache miss, retrieve it now |
| 14 | + request(config.PROBLEMS_URL, function(err, resp, body) { |
| 15 | + if (err) return cb(err); |
| 16 | + if (resp.statusCode != 200) return cb('Invalid HTTP response: ' + resp.statusCode); |
| 17 | + |
| 18 | + var $ = cheerio.load(body); |
| 19 | + items = $('#problemList tbody tr').map(function(){ |
| 20 | + var tds = $(this).children(); |
| 21 | + return { |
| 22 | + id: $(tds[1]).text(), |
| 23 | + name: $(tds[2]).children('a').text(), |
| 24 | + link: $(tds[2]).children('a').attr('href'), |
| 25 | + percent: $(tds[3]).text(), |
| 26 | + level: $(tds[6]).text() |
| 27 | + }; |
| 28 | + }).get(); |
| 29 | + |
| 30 | + cache.set('all', items); |
| 31 | + |
| 32 | + return cb(null, items); |
| 33 | + }); |
| 34 | +}; |
| 35 | + |
| 36 | +module.exports = problems; |
0 commit comments