Skip to content

Instantly share code, notes, and snippets.

@szpasztor
Last active November 3, 2022 15:00
Show Gist options
  • Save szpasztor/7c85966ad9ade7df86de4ee0c7e98e36 to your computer and use it in GitHub Desktop.
Save szpasztor/7c85966ad9ade7df86de4ee0c7e98e36 to your computer and use it in GitHub Desktop.
const toHHMM = (sec_num) => {
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
return `${hours}h ${minutes}m`;
}
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h * 60 * 60 * 1000));
return this;
}
Date.prototype.addMins = function(m) {
this.setTime(this.getTime() + (m * 60 * 1000));
return this;
}
const accessToken = 'YOUR_ACCESS_TOKEN'
const res = await fetch(`https://api.ouraring.com/v1/sleep?access_token=${accessToken}`)
const json = await res.json();
const nights = json.sleep;
const lastNight = nights[nights.length-1];
lastNight.awake_formatted = toHHMM(lastNight.awake);
lastNight.rem_formatted = toHHMM(lastNight.rem);
lastNight.light_formatted = toHHMM(lastNight.light);
lastNight.deep_formatted = toHHMM(lastNight.deep);
lastNight.bedtime_end_4h_threshold = new Date(lastNight.bedtime_end).addHours(4);
const now = new Date();
lastNight.add_to_calendar = lastNight.bedtime_end_4h_threshold < now &&
now < lastNight.bedtime_end_4h_threshold.addMins(4);
// If the ring wearer falls back asleep, the bedtime end time will be updated
// Consider sleep period completed if 4h has elapsed since period end
// Reason: The ring computes sleep results within four hours from the period end,
// but sleep analysis is always triggered when you open the application.
return lastNight;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment