Created
December 18, 2020 16:37
-
-
Save appy-one/257cc214d35525d8c9fa91cedf65a6b5 to your computer and use it in GitHub Desktop.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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