Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@solid-primitives/storage

Package Overview
Dependencies
Maintainers
2
Versions
45
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@solid-primitives/storage

Primitive that provides reactive wrappers for storage access

  • 1.0.10
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.5K
decreased by-63.68%
Maintainers
2
Weekly downloads
 
Created
Source

@solid-primitives/storage

lerna size size

Creates a primitive to reactively access both synchronous and asynchronous persistent storage APIs similar to localStorage.

Installation

npm install @solid-primitives/storage
# or
yarn add @solid-primitives/storage

How to use it

Basic Usage

createStorage is meant to wrap any localStorage-like API to be as accessible as a Solid Store. The main differences are

  • that this store is persisted in whatever API is used,
  • that you can only use the topmost layer of the object and
  • that you have additional methods in an object as the third part of the returned tuple:
const [store, setStore, {
  remove: (key: string) => void;
  clear: () => void;
  toJSON: () => ({ [key: string]: string });
}] = createStorage({ api: sessionStorage, prefix: 'my-app' });

setStore('key', 'value');
store.key; // 'value'

The props object support the following parameters:

api : an array of or a single localStorage-like storage API; default will be localStorage if it exists; an empty array or no API will not throw an error, but only ever get null and not actually persist anything

prefix : a string that will be prefixed every key inside the API on set and get operations

serializer / deserializer : a set of function to filter the input and output; the serializer takes an arbitrary object and returns a string, e.g. JSON.stringify, whereas the deserializer takes a string and returns the requested object again.

options : for APIs that support options as third argument in the getItem and setItem method (see helper type StorageWithOptions<O>), you can add options they will receive on every operation.


There are a number of convenience Methods primed with common storage APIs and our own version to use cookies:

createLocalStorage();
createSessionStorage();
createCookieStorage();

Asynchronous storage APIs

In case you have APIs that persist data on the server or via ServiceWorker in a CookieStore, you can wrap them into an AsyncStorage or AsyncStorageWithOptions API and use them with createAsyncStorage:

type CookieStoreOptions = {
  path: string;
  domain: string;
  expires: DOMTimeStamp;
  sameSite: "None" | "Lax" | "Strict"
}
const CookieStoreAPI: AsyncStorageWithOptions<CookieStoreOptions> = {
  getItem: (key) => cookieStore.get(key),
  getAll: () => cookieStore.getAll(),
  setItem: (key: string, value: string, options: CookieStoreOptions = {}) => cookieStore.set({
    ...options, name, value
  }),
  removeItem: (key) => cookieStore.delete(key),
  clear: async () => {
    const all = await cookieStore.getAll();
    for (const key of all) {
      await cookieStore.delete(key);
    }
  },
  key: async (index: number) => {
    const all = await cookieStore.getAll();
    return Object.keys(all)[index];
  }
});

const [cookies, setCookie, {
    remove: (key: string) => void;
    clear: () => void;
    toJSON: () => ({ [key: string]: string });
}] = createAsyncStorage({ api: CookieStoreAPI, prefix: 'my-app' });

await setStore('key', 'value');
await store.key; // 'value'

It works exactly like a synchronous storage, with the exception that you have to await every single return value. Once the CookieStore API becomes more prevalent, we will integrate support out of the box.

If you cannot use document.cookie, you can overwrite the entry point using the following tuple:

import { cookieStorage } from '@solid-primitives/storage';

cookieStorage._cookies = [object: { [name: string]: CookieProxy }, name: string];

If you need to abstract an API yourself, you can use a getter and a setter:

const CookieAbstraction = {
  get cookie() { return myCookieJar.toString() }
  set cookie(cookie) {
    const data = {};
    cookie.replace(/([^=]+)=(?:([^;]+);?)/g, (_, key, value) => { data[key] = value });
    myCookieJar.set(data);
  }
}
cookieStorage._cookies = [CookieAbstraction, 'cookie'];

createStorageSignal is meant for those cases when you only need to conveniently access a single value instead of full access to the storage API:

const [value, setValue] = createStorageSignal("value", { api: cookieStorage });

setValue("value");
value(); // 'value'

As a convenient additional method, you can also use createCookieStorageSignal(key, initialValue, options).


Tools

If you want to build your own Storage and don't want to do a .clear() method youself:

const storageWithClearMethod = addClearMethod(storage_without_clear_method);

Demo

TODO

Changelog

Expand Changelog

0.0.100

Initial release

1.0.0

First proper release of storage engine with CJS support.

1.0.7

Patch CJS support.

Keywords

FAQs

Package last updated on 05 Dec 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc