Socket
Socket
Sign inDemoInstall

browser-config

Package Overview
Dependencies
0
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.1.2 to 0.2.0

.babelrc

21

package.json
{
"name": "browser-config",
"version": "0.1.2",
"main": "build/index.js",
"version": "0.2.0",
"main": "./lib/index.js",
"license": "MIT",
"description": "localStorage/sessionStorage wrapper for convenient access.",
"keywords": [
"localStorage",
"sessionStorage",
"cache",
"browser permanent storage"
],
"author": {

@@ -16,9 +23,13 @@ "name": "Adil",

"scripts": {
"build": "tsc"
"build": "tsc --project tsconfig.build.json",
"test": "jest --env=jsdom"
},
"devDependencies": {
"@babel/preset-env": "^7.14.7",
"@babel/preset-typescript": "^7.14.5",
"@types/jest": "^26.0.24",
"jest": "^27.0.6",
"typescript": "^4.1.5"
},
"dependencies": {
}
"dependencies": {}
}
# Browser config
localStorage wrapper for convenient access.
You can use `localStorage` or `sessionStorage`. But is this convenient and performed like accessing property from an object ? No it's not.
## Examples
## Installation

@@ -9,32 +11,37 @@

Importing the library
```js
import BrowserConfig from "browser-config";
const config = new BrowserConfig();
import Store from "browser-config";
```
```js
const config = new Store();
// setting value
config.name = "Hello"
// By default it save data to the cache only and update/serialize data in next event loop.
// getting value
config.name // "hello"
// you can get config.name again and again it won't request to storage or deserialize,
// instead it will get data from the cache only.
[...Store.keys(config)] // ["name"]
// Store.keys return generators, you need to spread it to use as an array.
Object.fromEntries(config) // { name: "Hello" }
// or
Store.values(config) // { name: "Hello" }
// deleting
delete config.name //
delete config.name
config.name // undefined
// using getters and settings
// clearing all the data
Store.clear(config) // length of cleared items;
config.set('name', 'Hello');
config.get('name') // Hello
config.delete('name')
config.get('name') // undefined
config.name // undefined
// can support any serializable data
config.users = [{ name: 'Hello' }]
config.users // [{ name: 'Hello' }]

@@ -44,12 +51,12 @@

config.users.push({name: 'New User'}); // x will not work
// adding new value to array
config.users = [ ...config.users, {name: 'New User'} ]
config.users = [ ...config.users, { name: 'New User'}]
```
Multiple instances
## Multiple instances
```js
const config1 = new BrowserConfig('abcd'); // id
const config2 = new BrowserConfig('dcba'); // id
const config1 = new Store('abcd'); // id
const config2 = new Store('dcba'); // id

@@ -62,17 +69,102 @@ config1.name = 'Something'

config2.name // Something else
```
## Allow iterate
## Iterate through all the data
```js
const config = new BrowserConfig('default', true) // iterable
const config = new Store('default')
config.name = 'Something'
config.email = 'johndoe@example.com'
for (const [ key, value ] of config) {
console.log({ key, value }) // { key: 'email', value: 'Something' } and on
console.log({ key, value }) // { key: 'email', value: 'Something' } and so on...
}
```
## Session storage
By default it will save to localStorage and it is permanent, you can save it sessionStorage as well.
```ts
const config = new Store('some_id', {
validity: "session"
});
config.name = "Hello" // will be saved till browser closed.
```
## Typescript users
```ts
interface IPerson {
name?: string;
age?: number
}
const person = Store.create<IPerson>();
person.age = 'hello' // error
person.age = 20 // pass
```
## Custom driver
Sometimes you need to save data to other than localStorage, sessionStorage let's say in cookies.
```ts
import Store, { IDriver } from "browser-config";
class Driver implements IDriver {
set(key: string, val: string) {
// sourced from https://www.w3schools.com/js/js_cookies.asp
document.cookie = `${key}=${val}`;
return this;
}
get(key: string) {
// sourced from https://www.w3schools.com/js/js_cookies.asp
let name = key + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
}
remove(key: string) {
// sourced from https://www.w3schools.com/js/js_cookies.asp
document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
return this;
}
keys() {
// need to be implemented
}
}
const storage = new Store("1", { driver: new Driver() });
storage.data = 'hello';
expect(storage.data).toBe('hello');
```
## References
### instantiate
```ts
import Store from "browser-config";
const store = new Store(id, option)
```
* `id?: string` unique for unique storage
* `option?`
* `validity: "session" | "permanent"` validity of the data for particular storage, default is `permanent`.
* `driver: IDriver` custom driver
### static methods
* `Store.id(store): string` generated or passed id
* `Store.keys(store: Store): Iterable<string>` get all the keys
* `Store.values(store: Store): {[key: string]: any}` get all the values
* `Store.clear(store): string` clearing all the values
* `Store.update(store, data: object)` update values in bulk
* `Store.set(store, data: object)` it will delete all the existing value and set the provided object

@@ -1,89 +0,10 @@

type Key = string | number;
import BaseStorage, { IOption } from "./storage";
export type { IDriver } from "./driver";
export { BaseStorage };
class BrowserConfig<T = any> {
export default class BrowserConfig extends BaseStorage {
static create<T extends any>(id?: string, opt?: Partial<IOption>) {
return <T & BrowserConfig>new BrowserConfig(id, opt);
}
[key: string]: any;
public readonly _keyMaps = new Set<Key>();
constructor(public readonly id: string = BrowserConfig.name, private iterable = false) {
if (iterable) {
let keys: any = localStorage.getItem(`${id}.keys`);
if (keys) {
keys = JSON.parse(keys);
keys.forEach((val: string) => {
this._keyMaps.add(val)
});
}
}
return new Proxy(this, {
set(target, key, value) {
target.set(key as string, value);
return true;
},
get(target, property) {
if (property in target) {
return (target as any)[property as string];
}
return target.get(property as string);
},
deleteProperty(target, property) {
target.delete(property as string);
return true;
}
});
}
private updateKeys() {
localStorage.setItem(`${this.id}.keys`, JSON.stringify([...this._keyMaps.keys()]));
}
set(key: Key, value: T) {
if (this.iterable && !this._keyMaps.has(key)) {
this._keyMaps.add(key);
this.updateKeys();
}
localStorage.setItem(`${this.id}[${key}]`, JSON.stringify(value));
return this;
}
get(key: Key, def?: T) {
if (this.iterable && !this._keyMaps.has(key)) {
return def;
}
const val = localStorage.getItem(`${this.id}[${key}]`);
if (!val) {
return def;
}
return JSON.parse(val);
}
delete(key: Key) {
if (this.iterable && this._keyMaps.has(key)) {
this._keyMaps.delete(key);
this.updateKeys();
}
localStorage.removeItem(`${this.id}[${key}]`);
return this;
}
values() {
if (!this.iterable) {
throw new Error("Can't get values, dataset is not iterable");
}
const values: any = {};
for(const key of this._keyMaps.values()) {
values[key] = this.get(key);
}
return values;
}
keys() {
return [...this._keyMaps];
}
*[Symbol.iterator]() {
for (const key of this._keyMaps) {
yield [ key, this.get(key) ];
}
}
}
export default BrowserConfig;
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"target": "ES2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["DOM","es2015"], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"allowJs": false, /* Allow javascript files to be compiled. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./build/", /* Concatenate and emit output to single file. */
"outDir": "./build", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
"downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
"isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"noUnusedLocals": true, /* Report errors on unused locals. */
"noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
},
"exclude": ["lib"]
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc