Created
November 5, 2021 15:14
-
-
Save SamWSoftware/e4a1f088f71e0ef3e7b5700ed3e3298c to your computer and use it in GitHub Desktop.
Correct Usage of Global Variables
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
let cachedData = {}; | |
exports.handler = async (event) => { | |
if (cachedData && cachedData.expiresOn > Date.now() ) { | |
const response = { | |
statusCode: 200, | |
body: `The weather is ${cachedData.weather} and it is ${cachedData.temperature} decrees Celcius`, | |
}; | |
return response; | |
} | |
const { weather, temperature } = await fakeWeatherAPIRequest(event); | |
cachedData = { | |
weather, | |
temperature, | |
expiresOn: Date.now() + 30 * 1000 | |
}; | |
const response = { | |
statusCode: 200, | |
body: `The weather is ${weather} and it is ${temperature} decrees Celcius` | |
}; | |
return response; | |
}; | |
const fakeWeatherAPIRequest = async (event) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve({ | |
weather: 'sunny', | |
temperature: '15' | |
}); | |
}, 3000); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment