Skip to content

Commit

Permalink
feat(kvs/indexeddb): implement basic usage
Browse files Browse the repository at this point in the history
  • Loading branch information
azu committed Aug 7, 2020
1 parent d1a6d01 commit cc14444
Show file tree
Hide file tree
Showing 16 changed files with 472 additions and 13 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
packages/*/module
packages/*/lib
### https://raw.github.com/github/gitignore/d2c1bb2b9c72ead618c9f6a48280ebc7a8e0dff6/Node.gitignore

# Logs
Expand Down
3 changes: 3 additions & 0 deletions packages/indexeddb/.mocharc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"timeout": 30000
}
5 changes: 5 additions & 0 deletions packages/indexeddb/karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ module.exports = require("@jsdevtools/karma-config")({
module: {
rules: [{ test: /\.ts$/, use: "ts-loader" }]
}
},
client: {
mocha: {
timeout: 10 * 1000 // 30 sec
}
}
}
});
3 changes: 3 additions & 0 deletions packages/indexeddb/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
"tabWidth": 4,
"trailingComma": "none"
},
"dependencies": {
"@kvs/types": "^1.0.0"
},
"devDependencies": {
"@jsdevtools/karma-config": "^3.1.7",
"@types/mocha": "^8.0.1",
Expand Down
167 changes: 165 additions & 2 deletions packages/indexeddb/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,166 @@
export const kv = () => {
return window.indexedDB.open("toDoList", 1);
import type { KVS, KVSConstructor, KVSOptions } from "@kvs/types";

type IndexedDBKey = string;
const openDB = ({
name,
version,
tableName,
onUpgrade
}: {
name: string;
version: number;
tableName: string;
onUpgrade: ({ oldVersion, database }: { oldVersion: number; database: IDBDatabase }) => any;
}): Promise<IDBDatabase> => {
return new Promise((resolve, reject) => {
const openRequest = indexedDB.open(name, version);
openRequest.onupgradeneeded = function (event) {
const oldVersion = event.oldVersion;
const database = openRequest.result;
try {
database.createObjectStore(tableName);
} catch (e) {
reject(e);
}
// @ts-ignore
event.target.transaction.oncomplete = () => {
Promise.resolve(
onUpgrade({
oldVersion,
database
})
).then(() => {
return resolve(database);
});
};
};
openRequest.addEventListener("blocked", () => {
console.log("blocked");
reject(openRequest.error);
});
openRequest.onerror = function () {
console.log("blocked");
reject(openRequest.error);
};
openRequest.onsuccess = function () {
const db = openRequest.result;
resolve(db);
};
});
};
const getItem = <K extends IndexedDBKey, V>(database: IDBDatabase, tableName: string, key: K): Promise<V> => {
return new Promise((resolve, reject) => {
const transaction = database.transaction(tableName, "readonly");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.get(key);
request.onsuccess = () => {
resolve(request.result ? request.result : null);
};
request.onerror = () => {
reject(request.error);
};
});
};
const hasItem = async <K extends IndexedDBKey>(database: IDBDatabase, tableName: string, key: K): Promise<boolean> => {
const value = await getItem(database, tableName, key);
return value !== undefined;
};
const setItem = <K extends IndexedDBKey, V>(
database: IDBDatabase,
tableName: string,
key: K,
value: V
): Promise<void> => {
return new Promise((resolve, reject) => {
const transaction = database.transaction(tableName, "readwrite");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.put(value, key);
transaction.oncomplete = () => {
resolve();
};
transaction.onabort = () => {
reject(request.error ? request.error : transaction.error);
};
transaction.onerror = () => {
reject(request.error ? request.error : transaction.error);
};
});
};
const deleteItem = async <K extends IndexedDBKey>(
database: IDBDatabase,
tableName: string,
key: K
): Promise<boolean> => {
return new Promise((resolve, reject) => {
const transaction = database.transaction(tableName, "readwrite");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.delete(key);
transaction.oncomplete = () => {
resolve();
};
transaction.onabort = () => {
reject(request.error ? request.error : transaction.error);
};
transaction.onerror = () => {
reject(request.error ? request.error : transaction.error);
};
});
};
const clearItems = async (database: IDBDatabase, tableName: string): Promise<void> => {
return new Promise((resolve, reject) => {
const transaction = database.transaction(tableName, "readwrite");
const objectStore = transaction.objectStore(tableName);
const request = objectStore.clear();
transaction.oncomplete = () => {
resolve();
};
transaction.onabort = () => {
reject(request.error ? request.error : transaction.error);
};
transaction.onerror = () => {
reject(request.error ? request.error : transaction.error);
};
});
};
type IndexedDBOptions = {
tableName?: string;
};
const createStore = <K extends IndexedDBKey, V>(database: IDBDatabase, tableName: string) => {
const store = {
delete(key: K): Promise<boolean> {
return deleteItem(database, tableName, key).then(() => true);
},
get(key: K): Promise<V | undefined> {
return getItem(database, tableName, key);
},
has(key: K): Promise<boolean> {
return hasItem(database, tableName, key);
},
set(key: K, value: V) {
return setItem(database, tableName, key, value).then(() => store);
},
clear(): Promise<void> {
return clearItems(database, tableName);
},
__debug__database__: database
};
return store;
};
export const kvsIndexedDB: KVSConstructor<any, any> = async <K extends IndexedDBKey, V>(
options: KVSOptions<K, V> & IndexedDBOptions
): Promise<KVS<K, V>> => {
const { name, version, upgrade, ...indexDBOptions } = options;
const tableName = indexDBOptions.tableName ?? "kvs";
const database = await openDB({
name,
version,
tableName,
onUpgrade: ({ oldVersion, database }) => {
if (!upgrade) {
return;
}
return upgrade(createStore(database, tableName), oldVersion);
}
});
return createStore(database, tableName);
};
72 changes: 68 additions & 4 deletions packages/indexeddb/test/index-browser.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,71 @@
import { kv } from "../src/index";
import assert from "assert";
import { kvsIndexedDB } from "../src";
import { KVS } from "@kvs/types";

describe("kv-browser", () => {
it("should return open", () => {
console.log(kv());
let kvs: KVS<any, any>;
const databaseName = "kvs-test";
const forceDeleteDB = async () => {
// @ts-ignore
const dbs = await window.indexedDB.databases();
const deleteDB = (name: string) => {
return new Promise((resolve, reject) => {
const transaction = window.indexedDB.deleteDatabase(name);
transaction.addEventListener("success", () => {
resolve();
});
transaction.addEventListener("upgradeneeded", () => {
reject(transaction.error);
});
transaction.addEventListener("blocked", () => {
reject(transaction.error);
});
transaction.addEventListener("error", () => {
reject(transaction.error);
});
});
};
return Promise.all(dbs.map((db: any) => deleteDB(db.name)));
};
const deleteAllDB = async () => {
// clear all data
if (!kvs) {
await forceDeleteDB();
return;
}
return kvs.clear();
};
describe("@kvs/indexedDB", () => {
before(deleteAllDB);
afterEach(deleteAllDB);
it("set → get", async () => {
kvs = await kvsIndexedDB({
name: databaseName,
version: 1
});
await kvs.set("key", "value");
const result = await kvs.get("key");
assert.strictEqual(result, "value");
});
it("update with set", async () => {
kvs = await kvsIndexedDB({
name: databaseName,
version: 1
});
await kvs.set("key", "value1");
await kvs.set("key", "value2");
const result = await kvs.get("key");
assert.strictEqual(result, "value2");
});
it("test multiple key-value", async () => {
kvs = await kvsIndexedDB({
name: databaseName,
version: 1
});
await kvs.set("key1", "value1");
await kvs.set("key2", "value2");
const result1 = await kvs.get("key1");
const result2 = await kvs.get("key2");
assert.strictEqual(result1, "value1");
assert.strictEqual(result2, "value2");
});
});
4 changes: 2 additions & 2 deletions packages/indexeddb/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"esModuleInterop": true,
"newLine": "LF",
"outDir": "./lib/",
"target": "es5",
"target": "ES2015",
"sourceMap": true,
"declaration": true,
"jsx": "preserve",
Expand All @@ -33,4 +33,4 @@
".git",
"node_modules"
]
}
}
4 changes: 2 additions & 2 deletions packages/indexeddb/tsconfig.module.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "ESNext",
"outDir": "./module/",
"outDir": "./module/"
}
}
}
5 changes: 5 additions & 0 deletions packages/types/.mocharc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"require": [
"ts-node-test-register"
]
}
19 changes: 19 additions & 0 deletions packages/types/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2020 azu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
44 changes: 44 additions & 0 deletions packages/types/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# @kvs/types

A type definition for KVS.

## Install

Install with [npm](https://www.npmjs.com/):

npm install @kvs/types

## Usage

- [ ] Write usage instructions

## Changelog

See [Releases page](https://github.com/azu/kvs/releases).

## Running tests

Install devDependencies and Run `npm test`:

npm test

## Contributing

Pull requests and stars are always welcome.

For bugs and feature requests, [please create an issue](https://github.com/azu/kvs/issues).

1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D

## Author

- [github/azu](https://github.com/azu)
- [twitter/azu_re](https://twitter.com/azu_re)

## License

MIT © azu

0 comments on commit cc14444

Please sign in to comment.