Coding help needed: way to gracefully push data to DB before restarting

javascript
#1

Hello forum!

I’m building a bot that has ‘coins’ feature. I’m using Firebase Cloudstore to save the users’ data and it has an API calls limit, so I’ve decided to use npm package store, to obviously store users’ data while bot is awake, and then, when the project reloads, it should push data to Firebase.

I’ve found an answer by Glitch stuff about doing something before reloading project; i’m using this code:

// Flush coins to DB
process.on("SIGTERM", () => flush())

But there is a problem: when I don’t use process.exit(code) (as recommended), db gets its data, but if I do then nothing happens (but the flush() function executes.

Here is the code (and project: glitch/tihon/bin/coins.js):

const store = require("store")
const Coins = require("../lib/Coins")

 /**
 * Flushes coins to database
 */
function flush() {
  console.log("\n\n      Flushing coins to DB...\n\n")
  store.each((v, k) => {
    Coins.flush(k, v.data)
    console.log(k ,v)
  })
  
  // process.exit(0)
}

lib/Coins.js

module.exports.flush = (id, data) => {
  db.collection("coins")
    .doc(id)
    .set(data)
  console.log("Got", id)
}

Way it works:

Need help :no_mouth:

#2

Hey @jarvis394, in general projects will be forced to exit when they spends too long shutting down. You may want to have the flush happen on a timer, and on shutdown write the current state of the coins to a local file, and when the project starts back up, look for that file and sync the data then.

2 Likes
#3

Ok, thanks for the suggestion!