嗯,可能一进来大部分人都会以为,为何还会有人重复造轮子,GitHub第三方客户端都已经烂大街啦。确实,一开始我本身也是这么以为的,也问过本身是否真的有意义再去作这样一个项目。思考再三,如下缘由也决定了我愿意去作一个让本身满意的GitHub第三方客户端。javascript
目前实现的功能有:css
Gitter的初衷并非想把网页端全部功能照搬到小程序上,由于那样的体验并不会很友好,好比说,笔者本身也不想在手机上阅读代码,那将会是一件很痛苦的事。html
在保证用户体验的前提下,让用户用更简单的方式获得本身想要的,这是一件有趣的事。前端
第一次以为,在茫茫前端的世界里,本身是那么眇小。vue
当决定去作这个项目的时候,就开始了快马加鞭的技术选型,但摆在本身面前的选择是那么的多,也不得不感慨,前端的世界,真的很精彩。java
货比三家,通过一段时间的尝试及采坑,综合本身目前的能力,最终肯定了Gitter的技术选型:git
Taro + Taro UI + Redux + 云开发 Node.jsgithub
其实,做为一名Coder,曾经一直想找个UI设计师妹子作老婆的(确定有和我同样想法的Coder),多搭配啊。如今想一想,code不是生活的所有,如今的我同样很幸福。小程序
话回正题,没有设计师老婆页面设计怎么办?毕竟笔者想要的是一款高颜值的GitHub小程序。
嗯,不慌,默默的拿出了笔者沉寂已久的Photoshop和Sketch。不敢说本身的设计能力如何,Gitter的设计至少是能让笔者本身心情愉悦的,假若哪位设计爱好者想对Gitter的设计进行改良,欢迎欢迎,十二分的欢迎!微信小程序
Talk is cheap. Show me the code.
做为一篇技术性文章,怎可能少得了代码。
在这里主要写写几个采坑点,做为一个前端小白,相信各位读者均是笔者的前辈,还望多多指教!
进入开发阶段没多久,就遇到了第一个坑。GitHub竟然没有提供Trending列表的API!!!
也没有过多的去想GitHub为何不提供这个API,只想着怎么去尽快填好这个坑。一开始尝试使用Scrapy写一个爬虫对网页端的Trending列表信息进行定时爬取及存储供小程序端使用,但最终仍是放弃了这个作法,由于笔者并无服务器与已经备案好的域名,小程序的云开发也只支持Node.js的部署。
开源的力量仍是强大,最终找到了github-trending-api,稍做修改,成功部署到小程序云开发后台,在此,感谢原做者的努力。
async function fetchRepositories({ language = '', since = 'daily', } = {}) { const url = `${GITHUB_URL}/trending/${language}?since=${since}`; const data = await fetch(url); const $ = cheerio.load(await data.text()); return ( $('.repo-list li') .get() // eslint-disable-next-line complexity .map(repo => { const $repo = $(repo); const title = $repo .find('h3') .text() .trim(); const relativeUrl = $repo .find('h3') .find('a') .attr('href'); const currentPeriodStarsString = $repo .find('.float-sm-right') .text() .trim() || /* istanbul ignore next */ ''; const builtBy = $repo .find('span:contains("Built by")') .parent() .find('[data-hovercard-type="user"]') .map((i, user) => { const altString = $(user) .children('img') .attr('alt'); const avatarUrl = $(user) .children('img') .attr('src'); return { username: altString ? altString.slice(1) : /* istanbul ignore next */ null, href: `${GITHUB_URL}${user.attribs.href}`, avatar: removeDefaultAvatarSize(avatarUrl), }; }) .get(); const colorNode = $repo.find('.repo-language-color'); const langColor = colorNode.length ? colorNode.css('background-color') : null; const langNode = $repo.find('[itemprop=programmingLanguage]'); const lang = langNode.length ? langNode.text().trim() : /* istanbul ignore next */ null; return omitNil({ author: title.split(' / ')[0], name: title.split(' / ')[1], url: `${GITHUB_URL}${relativeUrl}`, description: $repo .find('.py-1 p') .text() .trim() || /* istanbul ignore next */ '', language: lang, languageColor: langColor, stars: parseInt( $repo .find(`[href="${relativeUrl}/stargazers"]`) .text() .replace(',', '') || /* istanbul ignore next */ 0, 10 ), forks: parseInt( $repo .find(`[href="${relativeUrl}/network"]`) .text() .replace(',', '') || /* istanbul ignore next */ 0, 10 ), currentPeriodStars: parseInt( currentPeriodStarsString.split(' ')[0].replace(',', '') || /* istanbul ignore next */ 0, 10 ), builtBy, }); }) ); }
async function fetchDevelopers({ language = '', since = 'daily' } = {}) { const data = await fetch( `${GITHUB_URL}/trending/developers/${language}?since=${since}` ); const $ = cheerio.load(await data.text()); return $('.explore-content li') .get() .map(dev => { const $dev = $(dev); const relativeUrl = $dev.find('.f3 a').attr('href'); const name = getMatchString( $dev .find('.f3 a span') .text() .trim(), /^\((.+)\)$/i ); $dev.find('.f3 a span').remove(); const username = $dev .find('.f3 a') .text() .trim(); const $repo = $dev.find('.repo-snipit'); return omitNil({ username, name, url: `${GITHUB_URL}${relativeUrl}`, avatar: removeDefaultAvatarSize($dev.find('img').attr('src')), repo: { name: $repo .find('.repo-snipit-name span.repo') .text() .trim(), description: $repo .find('.repo-snipit-description') .text() .trim() || /* istanbul ignore next */ '', url: `${GITHUB_URL}${$repo.attr('href')}`, }, }); }); }
exports.main = async (event, context) => { const { type, language, since } = event let res = null; let date = new Date() if (type === 'repositories') { const cacheKey = `repositories::${language || 'nolang'}::${since || 'daily'}`; const cacheData = await db.collection('repositories').where({ cacheKey: cacheKey }).orderBy('cacheDate', 'desc').get() if (cacheData.data.length !== 0 && ((date.getTime() - cacheData.data[0].cacheDate) < 1800 * 1000)) { res = JSON.parse(cacheData.data[0].content) } else { res = await fetchRepositories({ language, since }); await db.collection('repositories').add({ data: { cacheDate: date.getTime(), cacheKey: cacheKey, content: JSON.stringify(res) } }) } } else if (type === 'developers') { const cacheKey = `developers::${language || 'nolang'}::${since || 'daily'}`; const cacheData = await db.collection('developers').where({ cacheKey: cacheKey }).orderBy('cacheDate', 'desc').get() if (cacheData.data.length !== 0 && ((date.getTime() - cacheData.data[0].cacheDate) < 1800 * 1000)) { res = JSON.parse(cacheData.data[0].content) } else { res = await fetchDevelopers({ language, since }); await db.collection('developers').add({ data: { cacheDate: date.getTime(), cacheKey: cacheKey, content: JSON.stringify(res) } }) } } return { data: res } }
嗯,这是一个大坑。
在作技术调研的时候,发现小程序端Markdown解析主要有如下方案:
在Markdown解析这一块,最终采用的也是towxml,但发如今解析性能这一块,目前并非很优秀,对一些比较大的数据解析也超出了小程序所能承受的范围,还好贴心的做者(sbfkcel)提供了服务端的支持,在此感谢做者的努力!
最近这个项目🔥了,只能说跟不上年轻人的节奏了。
const Towxml = require('towxml'); const towxml = new Towxml(); // 云函数入口函数 exports.main = async (event, context) => { const { func, type, content } = event let res if (func === 'parse') { if (type === 'markdown') { res = await towxml.toJson(content || '', 'markdown'); } else { res = await towxml.toJson(content || '', 'html'); } } return { data: res } }
import Taro, { Component } from '@tarojs/taro' import PropTypes from 'prop-types' import { View, Text } from '@tarojs/components' import { AtActivityIndicator } from 'taro-ui' import './markdown.less' import Towxml from '../towxml/main' const render = new Towxml() export default class Markdown extends Component { static propTypes = { md: PropTypes.string, base: PropTypes.string } static defaultProps = { md: null, base: null } constructor(props) { super(props) this.state = { data: null, fail: false } } componentDidMount() { this.parseReadme() } parseReadme() { const { md, base } = this.props let that = this wx.cloud.callFunction({ // 要调用的云函数名称 name: 'parse', // 传递给云函数的event参数 data: { func: 'parse', type: 'markdown', content: md, } }).then(res => { let data = res.result.data if (base && base.length > 0) { data = render.initData(data, {base: base, app: this.$scope}) } that.setState({ fail: false, data: data }) }).catch(err => { console.log('cloud', err) that.setState({ fail: true }) }) } render() { const { data, fail } = this.state if (fail) { return ( <View className='fail' onClick={this.parseReadme.bind(this)}> <Text className='text'>load failed, try it again?</Text> </View> ) } return ( <View> { data ? ( <View> <import src='../towxml/entry.wxml' /> <template is='entry' data='{{...data}}' /> </View> ) : ( <View className='loading'> <AtActivityIndicator size={20} color='#2d8cf0' content='loading...' /> </View> ) } </View> ) } }
其实,笔者在该项目中,对Redux的使用并很少。一开始,笔者以为全部的接口请求都应该经过Redux操做,后面才发现,并非全部的操做都必须使用Redux,最后,在本项目中,只有获取我的信息的时候使用了Redux。
// 获取我的信息 export const getUserInfo = createApiAction(USERINFO, (params) => api.get('/user', params))
export function createApiAction(actionType, func = () => {}) { return ( params = {}, callback = { success: () => {}, failed: () => {} }, customActionType = actionType, ) => async (dispatch) => { try { dispatch({ type: `${customActionType }_request`, params }); const data = await func(params); dispatch({ type: customActionType, params, payload: data }); callback.success && callback.success({ payload: data }) return data } catch (e) { dispatch({ type: `${customActionType }_failure`, params, payload: e }) callback.failed && callback.failed({ payload: e }) } } }
getUserInfo() { if (hasLogin()) { userAction.getUserInfo().then(()=>{ Taro.hideLoading() Taro.stopPullDownRefresh() }) } else { Taro.hideLoading() Taro.stopPullDownRefresh() } } const mapStateToProps = (state, ownProps) => { return { userInfo: state.user.userInfo } } export default connect(mapStateToProps)(Index)
export default function user (state = INITIAL_STATE, action) { switch (action.type) { case USERINFO: return { ...state, userInfo: action.payload.data } default: return state } }
目前,笔者对Redux仍是处于只知其一;不知其二的状态,嗯,学习的路还很长。
当Gitter第一个版本经过审核的时候,心情是很激动的,就像本身的孩子同样,看着他一点一点的长大,笔者也很享受这样一个项目从无到有的过程,在此,对那些帮助过笔者的人一并表示感谢。
固然,目前功能和体验上可能有些不大完善,也但愿你们能提供一些宝贵的意见,Gitter走向完美的路上但愿有你!
最后,但愿Gitter小程序能对你有所帮助!