jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.29k stars 353 forks source link

should I call db.close() every time I finish doing something? #167

Closed ZYinMD closed 4 years ago

ZYinMD commented 4 years ago
async function add(thing) {
  const db1 = await openDB('db1', 1);
  db1.add('store1', thing);
  // db1.close() // should I add this?
}

If I'm calling add() quite frequently in my code, should I add the db1.close()? If I don't, would more and more open connections accumulate over time?

Another pattern may be export the db1 object and use it over and over for a long period of time, but I'm not sure if that's a good idea either.

Thanks very much!

jakearchibald commented 4 years ago

It's much better to reuse a single connection, so export a promise for db1.

habemuscode commented 1 year ago

Hi @jakearchibald

Using global variables dont give unexpected closed connections?

I tried to follow your example of Keyval store that you have in the README of this repo

I have a service worker with a few imports, for database, router, etc. I import the database file in one of the router files to get the JWT of the user and append it to the request to server

db.js

let currentVersion
export const database_name = 'shelter'
export const database_version = '1'

export const database_open = openDB(
  database_name,
  database_version,
  {
    async upgrade(db, oldVersion, newVersion, transaction, event) {
      console.log('Upgrading DB for version', oldVersion)
      ...
    },
    async blocked(currentVersion, blockedVersion, event) {
      console.log(`Please close this app opened in other browser tabs.`);
      await event.target.result.close()
    },
    async blocking(currentVersion, blockedVersion, event) {
      console.log(`App is outdated, please close this tab`);
      await event.target.result.close()
    },
    async terminated(event) {
      console.log('Terminated DB', event)
    }
  }
)

export const database_get = async (storeName, key) => (await database_open).get(storeName, Number(key))

router.js

import { database_get } from 'db.js'

const user = await database_get('user', 1)
if (!user) return Response.redirect('/login', 302)

When DevTools is closed, after some small time (20s?) the IndexedDB return undefined, so Im logged out. This NOT happen if, at least, I have one tab of browser with DevTools open.

Browser used for testing: Brave (Chromium) Service worker type module with ESM import/exports (Firefox don´t support this yet)