add: github搜索结果 (#1325)

closes #1289
This commit is contained in:
Chenyang Shi
2018-12-31 01:01:51 +08:00
committed by DIYgod
parent 644a86962d
commit a94c087f53
3 changed files with 57 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
const axios = require('../../utils/axios');
const cheerio = require('cheerio');
const url = require('url');
const host = 'https://github.com';
module.exports = async (ctx) => {
const query = ctx.params.query;
let sort = ctx.params.sort || 'bestmatch';
const order = ctx.params.order || 'desc';
if (sort === 'bestmatch') {
sort = '';
}
const suffix = 'search?o='.concat(order, '&q=', query, '&s=', sort, '&type=Repositories');
const link = url.resolve(host, suffix);
const response = await axios.get(link);
const $ = cheerio.load(response.data);
const out = $('.repo-list li')
.slice(0, 10)
.map(function() {
const single = {
title: $(this)
.find('div h3 a')
.text(),
link: host.concat(
$(this)
.find('div h3 a')
.attr('href')
),
description: $(this)
.find('div p')
.text()
.trim(),
};
return single;
})
.get();
ctx.state.data = {
title: `${query}的搜索结果`,
link: link,
item: out,
};
};