簡單嘮嘮
某乎問題:人這一生,應該養成哪些好習慣?
問題鏈接:https://www.zhihu.com/question/460674063
如果我來回答肯定會有定期運動的字眼。
平日里也有煅練的習慣,時間久了后一直想把運動數據公開,可惜某運動軟件未開放公共的接口出來。
幸運的是,在Github平臺沖浪我發現了有同行和我有類似的想法,并且已經用Python實現了他自己的運動主頁。
項目鏈接:https://github.com/yihong0618/running_page
Python嘛簡單,看明白后用Node.js折騰一波,自己擼兩個接口玩玩。
完成的運動頁面掛在我的博客網址。
我的博客:https://www.linglan01.cn
我的運動主頁:https://www.linglan01.cn/c/keep/index.html
Github地址:https://github.com/CatsAndMice/keep
梳理思路
平時跑步、騎行這兩項活動多,所以我只需要調用這兩個接口,再調用這兩個接口前需要先登錄獲取到token。
1. 登陸接口: https://api.gotokeep.com/v1.1/users/login 請求方法:post Content-Type: "application/x-www-form-urlencoded;charset=utf-8"2. 騎行數據接口:https://api.gotokeep.com/pd/v3/stats/detail?dateUnit=all&type=cycling&lastDate={last_date}請求方法: get Content-Type: "application/x-www-form-urlencoded;charset=utf-8"Authorization:`Bearer ${token}`3. 跑步數據接口:https://api.gotokeep.com/pd/v3/stats/detail?dateUnit=all&type=running&lastDate={last_date}請求方法: get Content-Type: "application/x-www-form-urlencoded;charset=utf-8"Authorization:`Bearer ${token}`
Node.js服務屬于代理層,解決跨域問題并再對數據包裹一層邏輯處理,最后發給客戶端。
不明白代理的同學可以看看這篇《Nginx之正、反向代理》
文章鏈接:https://linglan01.cn/post/47
運動數據總和
請求跑步接口方法:
getRunning.js
文件鏈接https://github.com/CatsAndMice/keep/blob/master/src/getRunning.js
const { headers } = require('./config');
const { isEmpty } = require("medash");
const axios = require('axios');module.exports = async (token, last_date = 0) => {if (isEmpty(token)) return {}headers["Authorization"] = `Bearer ${token}`;const result = await axios.get(`https://api.gotokeep.com/pd/v3/stats/detail?dateUnit=all&type=running&lastDate=${last_date}`, { headers })if (result.status === 200) {const { data: loginResult } = result;return loginResult.data;}return {};
}
請求騎行接口方法:
getRunning.js
文件鏈接 https://github.com/CatsAndMice/keep/blob/master/src/getCycling.js
const { headers } = require('./config');
const { isEmpty } = require("medash");
const axios = require('axios');module.exports = async (token, last_date = 0) => {if (isEmpty(token)) return {}headers["Authorization"] = `Bearer ${token}`;const result = await axios.get(`https://api.gotokeep.com/pd/v3/stats/detail?dateUnit=all&type=cycling&lastDate=${last_date}`, { headers })if (result.status === 200) {const { data: loginResult } = result;return loginResult.data;}return {};
}
現在要計算跑步、騎行的總數據,因此需要分別請求跑步、騎行的接口獲取到所有的數據。
getAllLogs.js
文件鏈接https://github.com/CatsAndMice/keep/blob/master/src/getAllLogs.js
const { isEmpty } = require('medash');module.exports = async (token, firstResult, callback) => {if (isEmpty(firstResult)||isEmpty(token)) {console.warn('請求中斷');return;}let { lastTimestamp, records = [] } = firstResult;while (1) {if (isEmpty(lastTimestamp)) break;const result = await callback(token, lastTimestamp)if (isEmpty(result)) break;const { lastTimestamp: lastTime, records: nextRecords } = resultrecords.push(...nextRecords);if (isEmpty(lastTime)) break;lastTimestamp = lastTime}return records
}
一個while
循環干到底,所有的數據都會被push
到records
數組中。
返回的records
數據再按年份分類計算某年的總騎行數或總跑步數,使用Map
做這類事別提多爽了。
getYearTotal.js
文件鏈接 https://github.com/CatsAndMice/keep/blob/master/src/getYearTotal.js
const { getYmdHms, mapToObj, each, isEmpty } = require('medash');
module.exports = (totals = []) => {const yearMap = new Map()totals.forEach((t) => {const { logs = [] } = tlogs.forEach(log => {if(isEmpty(log))returnconst { stats: { endTime, kmDistance } } = logconst { year } = getYmdHms(endTime);const mapValue = yearMap.get(year);if (mapValue) {yearMap.set(year, mapValue + kmDistance);return}yearMap.set(year, kmDistance);})})let keepRunningTotals = [];each(mapToObj(yearMap), (key, value) => {keepRunningTotals.push({ year: key, kmDistance: Math.ceil(value) });})return keepRunningTotals.sort((a, b) => {return b.year - a.year;});
}
處理過后的數據是這樣子的:
[{year:2023,kmDistance:99},{year:2022,kmDistance:66},//...
]
計算跑步、騎行的邏輯,唯一的變量為請求接口方法的不同,getAllLogs.js、getYearTotal.js
我們可以復用。
騎行計算總和:
cycling.js
文件鏈接https://github.com/CatsAndMice/keep/blob/master/src/cycling.js
const getCycling = require('./getCycling');
const getAllLogs = require('./getAllLogs');
const getYearTotal = require('./getYearTotal');module.exports = async (token) => {const result = await getCycling(token)const allCycling = await getAllLogs(token, result, getCycling);const yearCycling = getYearTotal(allCycling)return yearCycling
}
跑步計算總和:
run.js
文件鏈接 https://github.com/CatsAndMice/keep/blob/master/src/run.js
const getRunning = require('./getRunning');
const getAllRunning = require('./getAllLogs');
const getYearTotal = require('./getYearTotal');module.exports = async (token) => {const result = await getRunning(token)// 獲取全部的跑步數據const allRunning = await getAllRunning(token, result, getRunning);// 按年份計算跑步運動量const yearRunning = getYearTotal(allRunning)return yearRunning
}
最后一步,騎行、跑步同年份數據匯總。
src/index.js
文件鏈接https://github.com/CatsAndMice/keep/blob/master/src/index.js
const login = require('./login');
const getRunTotal = require('./run');
const getCycleTotal = require('./cycling');
const { isEmpty, toArray } = require("medash");
require('dotenv').config();
const query = {token: '',date: 0
}
const two = 2 * 24 * 60 * 60 * 1000
const data = { mobile: process.env.MOBILE, password: process.env.PASSWORD };
const getTotal = async () => {const diff = Math.abs(Date.now() - query.date);if (diff > two) {const token = await login(data);query.token = token;query.date = Date.now();}//Promise.all并行請求const result = await Promise.all([getRunTotal(query.token), getCycleTotal(query.token)])const yearMap = new Map();if (isEmpty(result)) return;if (isEmpty(result[0])) return;result[0].forEach(r => {const { year, kmDistance } = r;const mapValue = yearMap.get(year);if (mapValue) {mapValue.year = yearmapValue.data.runKmDistance = kmDistance} else {yearMap.set(year, {year, data: {runKmDistance: kmDistance,cycleKmDistance: 0}})}})if (isEmpty(result[1])) return;result[1].forEach(r => {const { year, kmDistance } = r;const mapValue = yearMap.get(year);if (mapValue) {mapValue.year = yearmapValue.data.cycleKmDistance = kmDistance} else {yearMap.set(year, {year, data: {runKmDistance: 0,cycleKmDistance: kmDistance}})}})return toArray(yearMap.values())
}
module.exports = {getTotal
}
getTotal
方法會將跑步、騎行數據匯總成這樣:
[{year:2023,runKmDistance: 999,//2023年,跑步總數據cycleKmDistance: 666//2023年,騎行總數據},{year:2022,runKmDistance: 99,cycleKmDistance: 66},//...
]
每次調用getTotal
方法都會調用login
方法獲取一次token。這里做了一個優化,獲取的token會被緩存2天省得每次都調,調多了登陸接口會出問題。
//省略
const query = {token: '',date: 0
}
const two = 2 * 24 * 60 * 60 * 1000
const data = { mobile: process.env.MOBILE, password: process.env.PASSWORD };
const getTotal = async () => {const diff = Math.abs(Date.now() - query.date);if (diff > two) {const token = await login(data);query.token = token;query.date = Date.now();}//省略
}//省略
最新動態
騎行、跑步接口都只請求一次,同年同月同日的騎行、跑步數據放在一起,最后按endTime
字段的時間倒序返回結果。
getRecentUpdates.js
文件鏈接 https://github.com/CatsAndMice/keep/blob/master/src/getRecentUpdates.js
const getRunning = require('./getRunning');
const getCycling = require('./getCycling');
const { isEmpty, getYmdHms, toArray } = require('medash');
module.exports = async (token) => {if (isEmpty(token)) returnconst recentUpdateMap = new Map();const result = await Promise.all([getRunning(token), getCycling(token)]);result.forEach((r) => {if (isEmpty(r)) return;const records = r.records || [];if (isEmpty(r.records)) return;records.forEach(rs => {rs.logs.forEach(l => {const { stats } = l;if (isEmpty(stats)) return;// 運動距離小于1km 則忽略該動態if (stats.kmDistance < 1) return;const { year, month, date, } = getYmdHms(stats.endTime);const key = `${year}年${month + 1}月${date}日`;const mapValue = recentUpdateMap.get(key);const value = `${stats.name} ${stats.kmDistance}km`;if (mapValue) {mapValue.data.push(value)} else {recentUpdateMap.set(key, {date: key,endTime: stats.endTime,data: [value]});}})})})return toArray(recentUpdateMap.values()).sort((a, b) => {return b.endTime - a.endTime})
}
得到的數據是這樣的:
[{date: '2023年8月12',endTime: 1691834351501,data: ['戶外跑步 99km','戶外騎行 99km']},//...
]
同樣的要先獲取token,在src/index.js
文件:
const login = require('./login');
const getRecentUpdates = require('./getRecentUpdates');
//省略
const getFirstPageRecentUpdates = async () => {const diff = Math.abs(Date.now() - query.date);if (diff > two) {const token = await login(data);query.token = token;query.date = Date.now();}return await getRecentUpdates(query.token);
}//省略
最新動態這個接口還是簡單的。
express創建接口
運動主頁由于我要將其掛到我的博客,因為端口不同會出現跨域問題,所以要開啟跨源資源共享(CORS)。
app.use((req, res, next) => {res.setHeader("Access-Control-Allow-Origin", "*");res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");res.setHeader('Content-Type', 'application/json;charset=utf8');next();
})
另外,我的博客網址使用的是https協議,Node.js服務也需要升級為https,否則會請求出錯。以前寫過一篇文章介紹Node.js升級https協議,不清楚的同學可以看看這篇《Node.js搭建Https服務 》文章鏈接https://linglan01.cn/post/47。
index.js
文件鏈接https://github.com/CatsAndMice/keep/blob/master/index.js
const express = require('express');
const { getTotal, getFirstPageRecentUpdates } = require("./src")
const { to } = require('await-to-js');
const fs = require('fs');
const https = require('https');
const path = require('path');
const app = express();
const port = 3000;
app.use((req, res, next) => {res.setHeader("Access-Control-Allow-Origin", "*");res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");res.setHeader('Content-Type', 'application/json;charset=utf8');next();
})
app.get('/total', async (req, res) => {const [err, result] = await to(getTotal())if (result) {res.send(JSON.stringify({ code: 200, data: result, msg: '請求成功' }));return}res.send(JSON.stringify({ code: 400, data: null, msg: '請求失敗' }));
})
app.get('/recent-updates', async (req, res) => {const [err, result] = await to(getFirstPageRecentUpdates())if (result) {res.send(JSON.stringify({ code: 200, data: result, msg: '請求成功' }));return}res.send(JSON.stringify({ code: 400, data: null, msg: '請求失敗' }));
})
const options = {key: fs.readFileSync(path.join(__dirname, './ssl/9499016_www.linglan01.cn.key')),cert: fs.readFileSync(path.join(__dirname, './ssl/9499016_www.linglan01.cn.pem')),
};
const server = https.createServer(options, app);
server.listen(port, () => {console.log('服務已開啟');
})
最后的話
貴在堅持,做好「簡單而正確」的事情,堅持是一項稀缺的能力,不僅僅是運動、寫文章,在其他領域,也是如此。
這段時間對投資、理財小有研究,堅持運動也是一種對身體健康的投資。
又完成了一篇文章,獎勵自己一頓火鍋。
如果我的文章對你有幫助,您的👍就是對我的最大支持_。
更多文章:http://linglan01.cn/about