Deno nuggets: In-memory DB (session storage)
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to use in-memory KV database in Deno?
set an item ('key', 'value');
get an item ('key');
remove an item ('key');
Solution
Imports
No imports are required.
Session Storage
Deno comes bundled with web’s standard in-memory global database called sessionStorage. This is the same data storage that’s available in browsers. This database stays in memory for the duration of the Deno application. Internally, sessionStorage is implemented through SQLite. (MDN docs).
The maximum size of sessionStorage database is 10MB (10485760 bytes)
- Length: Use length to get the number of items present in the sessionStorage
window.sessionStorage.length; //0
- Clear: Use clear to remove all the items from the sessionStorage
window.sessionStorage.clear();
- setItem: Use setItem to set a KV pair in the sessionStorage (only strings are allowed)
window.sessionStorage.setItem('K1', 'V1');
window.sessionStorage.setItem('K2', JSON.stringify({a: 1, b: '2'}));
- getItem: Use getItem to get the value associated with a key in the session storage (only strings are returned)
window.sessionStorage.getItem('K1'); //V1
window.sessionStorage.getItem('KN'); //null
- remoteItem: Use remoteItem to remove the KV pair for the given key (in-existent keys don’t raise error)
window.sessionStorage.removeItem('K1');
Complete code
Here is the complete code of using session storage:
window.sessionStorage.setItem('K1', 'V1');
window.sessionStorage.setItem('K2', JSON.stringify({a: 1, b: '2'}));window.sessionStorage.getItem('K1'); //V1
window.sessionStorage.getItem('K2')); //{"a":1,"b":"2"}
window.sessionStorage.getItem('K3'); //null
window.sessionStorage.length; //2window.sessionStorage.removeItem('K1');
window.sessionStorage.removeItem('K3');window.sessionStorage.getItem('K1'); //null
window.sessionStorage.getItem('K2'); //{"a":1,"b":"2"}window.sessionStorage.length; //1
window.sessionStorage.clear();
window.sessionStorage.length; //0