Consuming the API on the client side

Now that we have an API to fetch the last ten readings, we have to consume it on the client side. We add the following code to the public/script.j file:

    const fetchTemperatureHistory = () => {
      /**
       * Call the APi we created
       */
      fetch('/temperature/history')
        .then(results => {
          return results.json()
        })
        .then(data => {
          data.forEach(reading => {
            /**
             * For each reading present in the "data" array,
             * convert the time to the ISO Z format accepted 
by the javascript Date object * Format the time and push data on to the chart,
similar to the previous API calls */
const time = new Date(reading.createdAt + 'Z') const formattedTime = time.getHours() + ':' + time.getMinutes() + ':' +
time.getSeconds() pushData(temperatureChartConfig.data.labels,
formattedTime, 10) pushData(temperatureChartConfig.data.datasets[0]
.data, reading.value, 10) }) /** * Finally, update the chart after all readings have
been pushed */
temperatureChart.update() }) } fetchTemperatureHistory()

Similarly, we can add the functionality for humidity.

For the API, this is the code:

    app.get('/humidity/history', function (req, res) {
       databaseOperations.fetchLatestReadings('humidity', 10,
(err, results) => { if (err) { console.error(err) return res.status(500).end() } res.json(results.reverse()) }) })

And, for the client side, this is the code:

    const fetchHumidityHistory = () => {
      fetch('/humidity/history')
        .then(results => {
          return results.json()
        })
        .then(data => {
          data.forEach(reading => {
            const time = new Date(reading.createdAt + 'Z')
            const formattedTime =
            time.getHours() + ':' + time.getMinutes() + ':' +
time.getSeconds() pushData(humidityChartConfig.data.labels,
formattedTime, 10) pushData(humidityChartConfig.data.datasets[0].data,
reading.value, 10) }) humidityChart.update() }) } fetchHumidityHistory()

Restart your app and view it in the browser now. Every time you refresh the page, the chart readings stay. Furthermore, if you close your browser and open the app after some time, it will show you the latest 10 readings from the time before your opened your application. We just added persistence to our application. Awesome!

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

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