Upgrading the sensor interface module

The functionality defined in get-cached-sensor-readings.js was defined to fetch readings from our sensor and return it via a callback function. Now that we have our database in place, we want to store the readings in addition to returning them:

    const getSensorReadings = require('./get-sensor-readings')

    /**
     * Import the database module that we created earlier
     */
    const databaseOperations = require('./database-
operations'
) const cache = { temperature: 0, humidity: 0 } setInterval(() => { getSensorReadings((err, temperature, humidity) => { if (err) { return console.error(err) } /** * In addition to storing the readings in our cache,
we also store them in our database, using the methods
that we exported from our module */
databaseOperations.insertReading('temperature',
temperature) databaseOperations.insertReading('humidity', humidity) cache.temperature = temperature cache.humidity = humidity }) }, 2000) module.exports.getTemperature = () => cache.temperature module.exports.getHumidity = () => cache.humidity

One question that may arise is this: Why are we implementing this in get-cached-sensor-readings.js and not get-sensor-readings.js ?

As we have also seen in the previous chapters, one of our aims is to make the system as flexible as possible. The responsibility of the get-sensor-readings.js file was to interface with the external sensor and return the readings. The responsibility of get-cached-sensor-readings.js is to get readings and store them. Since storing readings in our database closely matches this responsibility, it makes sense to bundle the functionality here.

Furthermore, if we decided to change the sensor interface one day, we would also have to modify the code that was stored our readings. In the current situation, the code to interface with the sensor can change as long as the abstraction it provides is consistent.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.102.239