March
04
2025
IndexedDB Data Server
Plain JavaScript starter code to build indexedDB data server.
Takeaway Code
Infrastructure Code
js/infrastructure/models/
Script tags:
<script src="https://cdn.jsdelivr.net/gh/tmpmachine/vanilla-framework@f52bc8d/js/infrastructure/models/idb-connection.js"></script>
<script src="https://cdn.jsdelivr.net/gh/tmpmachine/vanilla-framework@f52bc8d/js/infrastructure/models/idb-wrapper.js"></script>
Application Code
Handle the database upgrade call.
js/application/indexed-db/onupgrade.js
function onUpgradeIDBEvt(event) {
let db = event.target.result;
let dbOldVersion = db.oldVersion ?? 0;
let storeNames = {
notes: 'notes',
};
if (dbOldVersion < 1) {
let storeName = storeNames.notes;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: 'id' });
}
}
}
Set up indexedDB connection and create a data server object with custom types.
js/application/servers.js
const dbName = 'app-v1-db';
const dbVersion = 1;
const dbConnection = new IdbConnection(dbName, dbVersion, onUpgradeIDBEvt);
// define store item types
/**
* @typedef {Object} Post
* @property {number} id
* @property {string} title
* @property {string} content
*/
// extend the IdbWrapper class with custom type
/** @extends IdbWrapper<Post> */
class PostsIdbStorage extends IdbWrapper {
constructor(dbConnection, storeName) {
super(dbConnection, storeName);
}
}
// pass in the idb connection and store name
let servPosts = new PostsIdbStorage(dbConnection, 'notes');
Usage
Add or update an item:
await servPosts.Put_({
id: Date.now().toString(),
content: 'First note',
});
Delete an item:
await servPosts.Delete_(id);
Clear store data:
await servPosts.Clear_();
Open comments page