Created
February 4, 2022 16:18
-
-
Save markshust/68e6803a06696a13f26c1c3621421528 to your computer and use it in GitHub Desktop.
Netlify function for countdown timer to specific date, stores in Nuxt Vuex store
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
| // Docs on event and context https://www.netlify.com/docs/functions/#the-handler-method | |
| const handler = async () => { | |
| try { | |
| // Note that time will always show 5 hours longer than prod, that is normal & expected. | |
| const dateFuture = new Date(new Date().getFullYear(), 1, 5, 5); // UTC is 5 hours ahead ET | |
| const dateNow = new Date(); | |
| const seconds = Math.floor((dateFuture - (dateNow))/1000); | |
| const minutes = Math.floor(seconds/60); | |
| const hours = Math.floor(minutes/60); | |
| const hoursMinutes = minutes - hours * 60 | |
| const timeLeft = `${hours}h ${hoursMinutes}m`; | |
| return { | |
| statusCode: 200, | |
| body: JSON.stringify({ timeLeft: timeLeft }), | |
| } | |
| } catch (error) { | |
| return { statusCode: 500, body: error.toString() } | |
| } | |
| } | |
| module.exports = { handler } |
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
| export default function({ $axios, store }) { | |
| const setTimeCountdown = function() { | |
| async function getTimeCountdown() { | |
| const url = process.env.nodeEnv === 'production' | |
| ? '/.netlify/functions/get-time-countdown/' | |
| : '/api/get-time-countdown/'; | |
| return await $axios.get(url); | |
| } | |
| getTimeCountdown().then(({data}) => { | |
| store.commit('time/setTimeLeft', data.timeLeft); | |
| }); | |
| }; | |
| setInterval(setTimeCountdown, 60000); | |
| setTimeCountdown(); | |
| } |
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
| export const state = () => ({ | |
| timeLeft: '0h 0m' | |
| }) | |
| export const mutations = { | |
| setTimeLeft(state, value) { | |
| state.timeLeft = value | |
| }, | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment