Last active
July 9, 2021 23:05
-
-
Save jkjustjoshing/c7bf97795c1c4a2567661b12c4b552ec to your computer and use it in GitHub Desktop.
Scrape connect.garmin.com sleep data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(async () => { | |
const dateStr = (dateObj) => `${dateObj.getUTCFullYear()}-${String(dateObj.getUTCMonth() + 1).padStart(2, '0')}-${String(dateObj.getUTCDate()).padStart(2, '0')}` | |
const getData = async (dateObj) => { | |
const date = dateStr(dateObj) | |
const username = '' | |
const resp = await fetch(`https://connect.garmin.com/modern/proxy/wellness-service/wellness/dailySleepData/${username}?date=${date}&nonSleepBufferMinutes=60`, { | |
"headers": { | |
"accept": "application/json, text/plain, */*", | |
"accept-language": "en-US,en;q=0.9", | |
"nk": "NT", | |
"sec-fetch-dest": "empty", | |
"sec-fetch-mode": "cors", | |
"sec-fetch-site": "same-origin", | |
"sec-gpc": "1", | |
"x-app-ver": "4.44.3.0" | |
}, | |
"referrer": `https://connect.garmin.com/modern/sleep/${date}`, | |
"referrerPolicy": "strict-origin-when-cross-origin", | |
"body": null, | |
"method": "GET", | |
"mode": "cors", | |
"credentials": "include" | |
}); | |
return resp.json() | |
} | |
const table = (objects) => { | |
const keys = Array.from(new Set(objects.flatMap(o => Object.keys(o)))) | |
let str = keys.join(',') + '\n' | |
str += objects.map(o => keys.map(k => o[k]).join(',')).join('\n') | |
return str | |
} | |
const startDate = '2021-01-01' | |
const endDate = '2021-07-08' | |
const dates = [] | |
let i = new Date(startDate) | |
while(i <= new Date(endDate)) { | |
dates.push(i) | |
i = new Date(i) | |
i.setUTCDate(i.getUTCDate() + 1) | |
} | |
const results = await Promise.all(dates.map(async d => { | |
const res = await getData(d) | |
const { | |
awakeSleepSeconds, | |
deepSleepSeconds, | |
lightSleepSeconds, | |
remSleepSeconds, | |
sleepTimeSeconds, | |
unmeasurableSleepSeconds | |
} = res.dailySleepDTO | |
return { | |
date: dateStr(d), | |
awakeSleepSeconds, | |
deepSleepSeconds, | |
lightSleepSeconds, | |
remSleepSeconds, | |
sleepTimeSeconds, | |
unmeasurableSleepSeconds | |
} | |
})) | |
console.log(table(results)) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment