Skip to content

Instantly share code, notes, and snippets.

@SamWSoftware
Created November 5, 2021 15:14
Show Gist options
  • Save SamWSoftware/e4a1f088f71e0ef3e7b5700ed3e3298c to your computer and use it in GitHub Desktop.
Save SamWSoftware/e4a1f088f71e0ef3e7b5700ed3e3298c to your computer and use it in GitHub Desktop.
Correct Usage of Global Variables
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