Skip to content

Commit

Permalink
feat: add close() to interface
Browse files Browse the repository at this point in the history
  • Loading branch information
azu committed Aug 8, 2020
1 parent 9cecad1 commit a269d1d
Show file tree
Hide file tree
Showing 18 changed files with 717 additions and 167 deletions.
5 changes: 5 additions & 0 deletions packages/indexeddb/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,11 @@ const createStore = <K extends IndexedDBKey, V>({
dropInstance(): Promise<void> {
return dropInstance(database, databaseName);
},
close() {
return Promise.resolve().then(() => {
database.close();
});
},
[Symbol.asyncIterator]() {
return iterator(database, tableName);
},
Expand Down
4 changes: 2 additions & 2 deletions packages/indexeddb/test/index-browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ describe("@kvs/indexedDB", () => {
});
await kvs.set("key1", "value1");
// close
kvs.__debug__database__.close();
await kvs.close();
// re-open and upgrade
kvs = await kvsIndexedDB({
...commonOptions,
Expand All @@ -192,7 +192,7 @@ describe("@kvs/indexedDB", () => {
});
await kvs.set("key1", "value1");
// close
kvs.__debug__database__.close();
await kvs.close();
// re-open and upgrade
kvs = await kvsIndexedDB({
...commonOptions,
Expand Down
3 changes: 3 additions & 0 deletions packages/localstorage/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
"tabWidth": 4,
"trailingComma": "none"
},
"dependencies": {
"@kvs/storage": "^1.0.0"
},
"devDependencies": {
"@jsdevtools/karma-config": "^3.1.7",
"@types/mocha": "^8.0.1",
Expand Down
171 changes: 8 additions & 163 deletions packages/localstorage/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,170 +1,15 @@
import type { KVS, KVSOptions } from "@kvs/types";
import { JsonValue } from "./JSONValue";
import { JsonValue, KvsStorage, kvsStorage, KVSStorageKey, KvsStorageOptions } from "@kvs/storage";
import { KVS, KVSOptions } from "@kvs/types";

type KVSStorageKey = string;
const getItem = <K extends KVSStorageKey>(storage: Storage, key: K) => {
const item = storage.getItem(key);
return item !== null ? JSON.parse(item) : undefined;
};
const hasItem = <K extends KVSStorageKey>(storage: Storage, key: K) => {
return storage.getItem(key) !== null;
};
const setItem = <K extends KVSStorageKey, V extends JsonValue | undefined>(storage: Storage, key: K, value: V) => {
// It is difference with IndexedDB implementation.
// This behavior compatible with localStorage.
if (value === undefined) {
return deleteItem(storage, key);
}
return storage.setItem(key, JSON.stringify(value));
};
const clearItem = (storage: Storage, kvsVersionKey: string) => {
const currentVersion: number | undefined = getItem(storage, kvsVersionKey);
// clear all
storage.clear();
// set kvs version again
if (currentVersion !== undefined) {
setItem(storage, kvsVersionKey, currentVersion);
}
};
const deleteItem = <K extends KVSStorageKey>(storage: Storage, key: K) => {
try {
storage.removeItem(key);
return true;
} catch {
return false;
}
};

function* createIterator<K extends KVSStorageKey, V extends JsonValue>(
storage: Storage,
kvsVersionKey: string
): Iterator<[K, V]> {
for (let i = 0; i < storage.length; i++) {
const key = storage.key(i);
if (!key) {
continue;
}
// skip meta key
if (key === kvsVersionKey) {
continue;
}
const value = getItem(storage, key);
yield [key, value] as [K, V];
}
}

const DEFAULT_KVS_VERSION = 1;
const openStorage = async ({
storage,
version,
kvsVersionKey,
onUpgrade
}: {
storage: Storage;
version: number;
kvsVersionKey: string;
onUpgrade: ({
oldVersion,
newVersion,
storage
}: {
oldVersion: number;
newVersion: number;
storage: Storage;
}) => any;
}) => {
const oldVersion = getItem(storage, kvsVersionKey);
if (oldVersion === undefined) {
setItem(storage, kvsVersionKey, DEFAULT_KVS_VERSION);
}
// if user set newVersion, upgrade it
if (oldVersion !== version) {
return Promise.resolve(
onUpgrade({
oldVersion,
newVersion: version,
storage
})
).then(() => {
return storage;
});
}
return storage;
};
const createStore = <K extends KVSStorageKey, V extends JsonValue>({
storage,
kvsVersionKey
}: {
storage: Storage;
kvsVersionKey: string;
}) => {
const store = {
get(key: K): Promise<V | undefined> {
return Promise.resolve().then(() => {
return getItem(storage, key);
});
},
has(key: K): Promise<boolean> {
return Promise.resolve().then(() => {
return hasItem(storage, key);
});
},
set(key: K, value: V | undefined): Promise<KVS<K, V>> {
return Promise.resolve()
.then(() => {
return setItem(storage, key, value);
})
.then(() => {
return store;
});
},
clear(): Promise<void> {
return Promise.resolve().then(() => {
return clearItem(storage, kvsVersionKey);
});
},
delete(key: K): Promise<boolean> {
return Promise.resolve().then(() => {
return deleteItem(storage, key);
});
},
[Symbol.asyncIterator](): AsyncIterator<[K, V]> {
const iterator = createIterator<K, V>(storage, kvsVersionKey);
return {
next() {
return Promise.resolve().then(() => {
return iterator.next();
});
}
};
}
};
return store;
};
export type KvsStorage<K extends KVSStorageKey, V extends JsonValue> = KVS<K, V>;
export type KvsStorageOptions<K extends KVSStorageKey, V extends JsonValue> = KVSOptions<K, V> & {
export type KvsLocalStorage<K extends KVSStorageKey, V extends JsonValue> = KVS<K, V>;
export type KvsLocalStorageOptions<K extends KVSStorageKey, V extends JsonValue> = KVSOptions<K, V> & {
kvsVersionKey?: string;
storage: Storage;
};
export const kvsStorage = async <K extends KVSStorageKey, V extends JsonValue>(
export const kvsLocalStorage = async <K extends KVSStorageKey, V extends JsonValue>(
options: KvsStorageOptions<K, V>
): Promise<KvsStorage<K, V>> => {
const { name, version, upgrade, ...kvStorageOptions } = options;
const kvsVersionKey = kvStorageOptions.kvsVersionKey ?? "__kvs_version__";
const storage = await openStorage({
storage: options.storage,
version: options.version,
onUpgrade: ({ oldVersion, newVersion, storage }) => {
if (!options.upgrade) {
return;
}
return options.upgrade({
kvs: createStore({ storage, kvsVersionKey }),
newVersion,
oldVersion
});
},
kvsVersionKey
return kvsStorage({
...options,
storage: window.localStorage
});
return createStore({ storage, kvsVersionKey });
};
5 changes: 5 additions & 0 deletions packages/storage/.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/storage/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/storage/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# @kvs/storage

localstorage for KVS.

## Install

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

npm install @kvs/storage

## 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
34 changes: 34 additions & 0 deletions packages/storage/karma.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module.exports = require("@jsdevtools/karma-config")({
tests: ["src/**/*.ts", "test/**/*.test.ts"],
browsers: Boolean(process.env.CI)
? {
firefox: true,
chrome: true,
safari: true
// MSEdge does not work correctly
// edge: false,
}
: {
// manually attach to test bed
firefox: false,
chrome: false,
edge: false,
safari: false
},
config: {
webpack: {
resolve: {
extensions: [".js", ".jsx", ".ts", ".tsx"]
},
mode: "development",
module: {
rules: [{ test: /\.ts$/, use: "ts-loader" }]
}
},
client: {
mocha: {
timeout: 5 * 1000 // 5 sec
}
}
}
});
63 changes: 63 additions & 0 deletions packages/storage/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"name": "@kvs/storage",
"version": "1.0.0",
"description": "Storage(localStorage, sessionStorage) helper for KVS.",
"keywords": [
"kvs",
"browser",
"localstorage"
],
"homepage": "https://github.com/azu/kvs/tree/master/packages/localstorage/",
"bugs": {
"url": "https://github.com/azu/kvs/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/azu/kvs.git"
},
"license": "MIT",
"author": "azu",
"sideEffects": false,
"main": "lib/index.js",
"module": "module/index.js",
"types": "lib/index.d.ts",
"directories": {
"lib": "lib",
"test": "test"
},
"files": [
"bin/",
"lib/",
"module"
],
"scripts": {
"build": "tsc -p . && tsc --project ./tsconfig.module.json",
"clean": "rimraf lib/ module/",
"prettier": "prettier --write \"**/*.{js,jsx,ts,tsx,css}\"",
"prepublish": "npm run clean && npm run build",
"test": "karma start --single-run",
"watch": "tsc -p . --watch"
},
"prettier": {
"printWidth": 120,
"singleQuote": false,
"tabWidth": 4,
"trailingComma": "none"
},
"devDependencies": {
"@jsdevtools/karma-config": "^3.1.7",
"@types/mocha": "^8.0.1",
"@types/node": "^14.0.27",
"karma": "^5.1.1",
"karma-cli": "^2.0.0",
"lerna": "^3.22.1",
"mocha": "^8.1.1",
"prettier": "^2.0.5",
"rimraf": "^3.0.2",
"ts-loader": "^8.0.2",
"typescript": "^3.9.7"
},
"publishConfig": {
"access": "public"
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
// Based on https://github.com/sindresorhus/type-fest/blob/master/source/basic.d.ts
export type Primitive = null | undefined | string | number | boolean | symbol | bigint;

/**
Matches a JSON object.
This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`.
Expand Down

0 comments on commit a269d1d

Please sign in to comment.