Skip to content

Instantly share code, notes, and snippets.

@appy-one

appy-one/db.js

Created Dec 18, 2020
Embed
What would you like to do?
Using AceBase instead of Dexie.js to store sticky notes in the browser's IndexedDB. See Andy Haskell's IndexedDB tutorial Part 4 at https://dev.to/andyhaskell/using-dexie-js-to-write-slick-indexeddb-code-304o
let { AceBase } = require('acebase');
// Database contains all IndexedDB database logic for our web app.
class Database {
// The constructor opens/creates the database titled 'my_db_(namespace)'
constructor(namespace) {
// Use AceBase.WithIndexedDB to create an AceBase instance
// that uses IndexedDB to store its data
let name = Database.dbName(namespace);
let db = AceBase.WithIndexedDB(name, { logLevel: 'log' });
// Keep a reference to the notes node
this.notes = db.ref('notes');
}
// addStickyNote adds a sticky note with the text passed in to the "notes"
// object store. Returns a promise that resolves when the sticky note is
// successfully added.
addStickyNote(message) {
return this.notes.push({
text: message,
timestamp: new Date(),
});
}
// getNotes retrieves all sticky notes from the "notes" object store. Returns
// a promise that resolves when we successfully retrieve the sticky notes,
// giving us the notes in an array.
getNotes(reverseOrder) {
return this.notes
.query()
.sort('timestamp', !reverseOrder)
.get()
.then(snaps => snaps.getValues());
}
// dbName sets up the name of the database using an optional namespace
// parameter for test coverage.
static dbName(namespace) {
return namespace != undefined ?
`my_db_${namespace}` :
'my_db';
}
}
module.exports = Database;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment