0.3.0 • Published 6 years ago
@yagisumi/sqlite3-storage v0.3.0
@yagisumi/sqlite3-storage
A simple key-value store like localStorage using better-sqlite3.
Installation
$ npm i @yagisumi/sqlite3-storage
Usage
- javascript
const Database = require('@yagisumi/sqlite3-storage').Database;
const db = new Database(':memory:');
const storage = db.getStorage('foo');
storage.setItem('key1', 'value1');
let v = storage.getItem('key1');
for (let kv of storage) {
console.log(kv.key, kv.value);
}
storage.clear();
- typescript
import { Database } from '@yagisumi/sqlite3-storage';
// ...
Remarks
Note that SQLite3 exceptions can be thrown from anywhere.
When setting many items, you should do in a transaction. Otherwise it takes a lot of time.
db.transaction({ rollback: false }, () => {
for (let i = 0; i < 100; i++) {
storage.setItem(`key${i}`, `value${i}`)
}
})
Example
example with typescript
import { Database, Sqlite3Storage } from "@yagisumi/sqlite3-storage"
import serialijse from "serialijse"
class Store<T> {
constructor(private storage: Sqlite3Storage.Storage) {}
set(key: string, obj: T) {
this.storage.setItem(key, serialijse.serialize(obj))
}
get(key: string) {
const v = this.storage.getItem(key)
if (v) {
return serialijse.deserialize<T>(v)
} else {
return null
}
}
}
class Person {
constructor(readonly name: string, readonly age: number) {}
}
serialijse.declarePersistable(Person)
const db = new Database("temp.db")
const storage = db.getStorage("people")
const store = new Store<Person>(storage)
const people = [new Person("Mike", 39), new Person("Bob", 44)]
db.transaction(null, () => {
for (let p of people) {
store.set(p.name, p)
}
})
for (let p of people) {
console.log(store.get(p.name))
}
API Reference
class Database {
constructor(path_or_sqlite3: string | BetterSqlite3.Database, options?: Sqlite3Storage.DatabaseOptions);
readonly inTransaction: boolean;
close(): void;
getStorage(name: string): Sqlite3Storage.Storage;
transaction(options: Sqlite3Storage.TransactionOptions | null | undefined, func: () => void): void;
}
namespace Sqlite3Storage {
interface Storage {
readonly db: Database;
readonly storageName: string;
readonly length: number;
clear(): void;
getItem(key: string): string | null;
key(index: number): string | null;
at(index: number): KeyValue | null;
removeItem(key: string): void;
setItem(key: string, value: string): void;
}
interface KeyValue {
key: string;
value: string;
}
interface DatabaseOptions {
// better-sqlite3 options
memory?: boolean;
readonly?: boolean;
fileMustExist?: boolean;
timeout?: number;
verbose?: (message?: any, ...additionalArgs: any[]) => void;
}
interface TransactionOptions {
rollback?: boolean; // default: true
type?: TransactionType; // "DEFERRED" | "IMMEDIATE" | "EXCLUSIVE"
}
}
Documentation
https://yagisumi.github.io/node-sqlite3-storage/