Refactoring code for new reading

Removed code that runs after a new reading has been received from the 
express model, and added it as a sequelize hook instead.
This commit is contained in:
JayWll 2020-04-25 14:06:48 -06:00
parent 9c8b2d45c1
commit 7612cb4fee
2 changed files with 73 additions and 67 deletions

View File

@ -1,7 +1,6 @@
// Initialize project // Initialize project
const db = require('./db/db') const db = require('./db/db')
const path = require('path') const path = require('path')
const twit = require('twit')
require('dotenv').config({path: path.join(__dirname, '../.env')}) require('dotenv').config({path: path.join(__dirname, '../.env')})
const express = require('express'); const express = require('express');
const app = express(); const app = express();
@ -18,72 +17,6 @@ app.get('/newreading', (req, res) => {
db.Readings.create({ timestamp: new Date(), reading: req.query.v }); db.Readings.create({ timestamp: new Date(), reading: req.query.v });
res.status(200).send('Reading received: ' + req.query.v).end(); res.status(200).send('Reading received: ' + req.query.v).end();
// Fetch all settings
db.Settings.findAll().then((result) => {
// Reset low moisture flag if it's set, and the reading is greater than high-trigger
if (result.find(o => o.dataValues.key === 'low').dataValues.value !== '0' && req.query.v >= parseInt(result.find(o => o.dataValues.key === 'high-trigger').dataValues.value)) {
// Pick a random message from the array below
const tweet = [
'Thanks to whoever watered me just now!! So moist.',
'So refreshing! Thank you, mysterious stranger, for the life-giving liquidy sustenance.',
'Whoever watered me (I\'m kind of guessing it was you, @Katheryn_mur), know that I appreciate it!'
]
// Define options for the twitter API
const msg = new twit({
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
access_token: process.env.ACCESS_TOKEN,
access_token_secret: process.env.ACCESS_TOKEN_SECRET
})
msg.post('statuses/update', { status: tweet[Math.floor(Math.random() * tweet.length)] })
// Update low to false
db.Settings.update({ value: false }, { where: { key: 'low' } })
// Update alert to false
db.Settings.update({ value: false }, { where: { key: 'alert' } })
}
// Set the low moisture flag if it's not set, and the value is less than low-trigger
if (result.find(o => o.dataValues.key === 'low').dataValues.value === '0' && req.query.v <= parseInt(result.find(o => o.dataValues.key === 'low-trigger').dataValues.value)) {
// Update low to true
db.Settings.update({ value: new Date().toISOString() }, { where: { key: 'low' } })
}
// If the low moisture flag is set but an alert has not yet been sent, determine if an alert is necessarry
if (result.find(o => o.dataValues.key === 'low').dataValues.value !== '0' && result.find(o => o.dataValues.key === 'alert').dataValues.value === '0') {
const lowtriggered = new Date().getTime() - new Date(result.find(o => o.dataValues.key === 'low').dataValues.value).getTime()
const fourdays = 4 * 24 * 60 * 60 * 1000
// If the first low reading was more than 5 days ago, send an alert
if (lowtriggered > fourdays) {
// Pick a random message from the array below
const tweet = [
'I\'m getting pretty thirsty over here, @JayWll',
'So. Very. Dry. You know I\'m a succulent not a cactus, right @JayWll? 🌵',
'Hey @JayWll, water me. 🥛',
'They say a man shall not live by bread alone, and a succulent won\'t live if you don\'t WATER ME @JAYWLL!!1! 🍞🚰💦',
'@JayWll seriously bro. A little water. That\'s all I ask.'
]
// Define options for the twitter API
const msg = new twit({
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
access_token: process.env.ACCESS_TOKEN,
access_token_secret: process.env.ACCESS_TOKEN_SECRET
})
// Post a tweet
msg.post('statuses/update', { status: tweet[Math.floor(Math.random() * tweet.length)] })
// Flag that an alert has been sent
db.Settings.update({ value: new Date().toISOString() }, { where: { key: 'alert' } })
} else console.log('Low for less than 5 days')
} else console.log('No message needed')
})
}); });
// Handle requests for /getdata by returning a JSON object of data for the relevant time period // Handle requests for /getdata by returning a JSON object of data for the relevant time period

View File

@ -1,5 +1,8 @@
const Sequelize = require('sequelize') const Sequelize = require('sequelize')
const Op = Sequelize.Op const Op = Sequelize.Op
const path = require('path')
const twit = require('twit')
require('dotenv').config({path: path.join(__dirname, '../../.env')})
// Setup database, using credentials set in .env // Setup database, using credentials set in .env
const sequelize = new Sequelize('database', process.env.DB_USER, process.env.DB_PASS, { const sequelize = new Sequelize('database', process.env.DB_USER, process.env.DB_PASS, {
@ -16,6 +19,76 @@ const Readings = sequelize.define('readings', {
reading: { reading: {
type: Sequelize.INTEGER type: Sequelize.INTEGER
} }
}, {
hooks: {
afterCreate: (data, opts) => {
// Fetch all settings
Settings.findAll().then((result) => {
// Reset low moisture flag if it's set, and the reading is greater than high-trigger
if (result.find(o => o.dataValues.key === 'low').dataValues.value !== '0' && data.reading >= parseInt(result.find(o => o.dataValues.key === 'high-trigger').dataValues.value)) {
// Pick a random message from the array below
const tweet = [
'Thanks to whoever watered me just now!! So moist.',
'So refreshing! Thank you, mysterious stranger, for the life-giving liquidy sustenance.',
'Whoever watered me (I\'m kind of guessing it was you, @Katheryn_mur), know that I appreciate it!'
]
// Define options for the twitter API
const msg = new twit({
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
access_token: process.env.ACCESS_TOKEN,
access_token_secret: process.env.ACCESS_TOKEN_SECRET
})
msg.post('statuses/update', { status: tweet[Math.floor(Math.random() * tweet.length)] })
// Update low to false
db.Settings.update({ value: false }, { where: { key: 'low' } })
// Update alert to false
db.Settings.update({ value: false }, { where: { key: 'alert' } })
}
// Set the low moisture flag if it's not set, and the value is less than low-trigger
if (result.find(o => o.dataValues.key === 'low').dataValues.value === '0' && data.reading <= parseInt(result.find(o => o.dataValues.key === 'low-trigger').dataValues.value)) {
// Update low to true
db.Settings.update({ value: new Date().toISOString() }, { where: { key: 'low' } })
}
// If the low moisture flag is set but an alert has not yet been sent, determine if an alert is necessarry
if (result.find(o => o.dataValues.key === 'low').dataValues.value !== '0' && result.find(o => o.dataValues.key === 'alert').dataValues.value === '0') {
const lowtriggered = new Date().getTime() - new Date(result.find(o => o.dataValues.key === 'low').dataValues.value).getTime()
const fourdays = 4 * 24 * 60 * 60 * 1000
// If the first low reading was more than 5 days ago, send an alert
if (lowtriggered > fourdays) {
// Pick a random message from the array below
const tweet = [
'I\'m getting pretty thirsty over here, @JayWll',
'So. Very. Dry. You know I\'m a succulent not a cactus, right @JayWll? 🌵',
'Hey @JayWll, water me. 🥛',
'They say a man shall not live by bread alone, and a succulent won\'t live if you don\'t WATER ME @JAYWLL!!1! 🍞🚰💦',
'@JayWll seriously bro. A little water. That\'s all I ask.'
]
// Define options for the twitter API
const msg = new twit({
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
access_token: process.env.ACCESS_TOKEN,
access_token_secret: process.env.ACCESS_TOKEN_SECRET
})
// Post a tweet
msg.post('statuses/update', { status: tweet[Math.floor(Math.random() * tweet.length)] })
// Flag that an alert has been sent
db.Settings.update({ value: new Date().toISOString() }, { where: { key: 'alert' } })
} else console.log('Low for less than 5 days')
} else console.log('No message needed')
})
}
}
}) })
// Define 'settings' table structure // Define 'settings' table structure