gundb / gun-level

LevelDB storage plugin for gunDB
75 stars 15 forks source link

With indexeddb, retrieving data from a node after a browser refresh returns undefined #42

Open dfreire opened 6 years ago

dfreire commented 6 years ago

I detected a problem when trying to use gun in the browser with indexeddb. Apparently, I cannot get data from a node after a browser refresh.

This is the localStorage implementation, which works fine:

// setup with localStorage
const gun = Gun();

// run
gun.get('something').val() // undefined as expected
gun.get('something').put({ timestamp: Date.now() })
gun.get('something').val() // timestamp as expected

// refresh
gun.get('something').val() // timestamp as expected

This is the indexeddb implementation, which has the problem: (same thing with level-js and fruitdown)

// setup with indexedDB
const Gun = require('gun-level');
const levelup = require('levelup');
const leveldown = require('level-js');
const db = leveldown('my-big-db');
db.status = 'unknown'; // see https://github.com/Level/level.js/issues/59
const gun = Gun({
  localStorage: false,
  level: levelup(db),
});

// run
gun.get('something').val() // undefined as expected
gun.get('something').put({ timestamp: Date.now() })
gun.get('something').val() // timestamp as expected

// refresh
gun.get('something').val() // undefined !!
// wait a lot of time
gun.get('something').val() // still undefined !!
// write again, then read
gun.get('something').put({ timestamp: Date.now() })
gun.get('something').val() // timestamp as expected
dfreire commented 6 years ago

Actually, my bad!! After reading more docs I finally realized the problem was in not using encoding-down

Fixed my setup:

// setup with indexedDB
const Gun = require('gun-level');
const levelup = require('levelup');
const leveldown = require('level-js');
const encode = require('encoding-down');
const db = leveldown('my-big-db');
const gun = Gun({
    localStorage: false,
    level: levelup(encode(db, { valueEncoding: 'json' })),
});

Furthermore, the db.status = 'unknown'; hack is no longer necessary 👍

amark commented 6 years ago

Is this working @dfreire ?

dfreire commented 6 years ago

Yes, the issue can be closed (as it was not an issue).

However, maybe the snippet above could placed somewhere to document the explicit case of using indexeddb in the browser?

amark commented 6 years ago

That is a great idea, could you make a PR to the README of this repo? Then I'll accept it!