Skip to content

Instantly share code, notes, and snippets.

@Slurpgoose
Last active September 29, 2020 17:28
Show Gist options
  • Save Slurpgoose/03e1ff9c4ada53f10f6aa73c2d646770 to your computer and use it in GitHub Desktop.
Save Slurpgoose/03e1ff9c4ada53f10f6aa73c2d646770 to your computer and use it in GitHub Desktop.
Manage node state with redis.
var redis = require('redis');
var client = redis.createClient(); //redis.createClient(port, host, options)
const key = 'test'; //redis key name
//Error handling
client.on("error", (err) => {
console.log(`Error: ${err}`);
});
// set inital state to an empty object {}
client.set(key, JSON.stringify({}));
//replicate state updates using setInterval
setInterval(() => {
//mock state update.
const newObject = {
[Math.floor(Math.random() * 10) + 100)] : Math.floor(Math.random() * 5000) + 1,
[Math.floor(Math.random() * 10) + 100)] : Math.floor(Math.random() * 5000) + 1,
[Math.floor(Math.random() * 10) + 100)] : Math.floor(Math.random() * 5000) + 1,
}
// get key from redis
client.get(key, (err, data) => {
//convert string to native object
let prevState = JSON.parse(data);
//use spread operator to concat two objects
let newState = {
...prevState,
...newObject,
};
//set key to newState
client.set(key, JSON.stringify(newState));
console.log(state)
});
}, 500)
// quit client on CTRL + C
process.on('SIGINT', () => {
client.quit();
console.log('smooth exit redis')
process.exit(0);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment