54 lines
1.6 KiB
Markdown
54 lines
1.6 KiB
Markdown
|
# varasto
|
||
|
|
||
|
[![Package Version](https://img.shields.io/hexpm/v/varasto)](https://hex.pm/packages/varasto)
|
||
|
[![Hex Docs](https://img.shields.io/badge/hex-docs-ffaff3)](https://hexdocs.pm/varasto/)
|
||
|
|
||
|
Typed access to the [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API), i.e. LocalStorage and SessionStorage.
|
||
|
|
||
|
This package is only for the JavaScript target. It depends on [plinth](https://hexdocs.pm/plinth/index.html), which implements the lower level (string only) Web Storage API access. Thus, if you only intend to read and write string values, you may use plinth directly.
|
||
|
|
||
|
## Usage
|
||
|
|
||
|
Varasto uses JSON as the storage format. To use it, you will need to construct a `TypedStorage` value that encapsulates a reader and a writer to convert the value to and from `gleam/json.Json`.
|
||
|
|
||
|
An example where the data type is a list of integers:
|
||
|
|
||
|
```gleam
|
||
|
import gleam/dynamic
|
||
|
import gleam/json
|
||
|
import plinth/javascript/storage
|
||
|
import varasto
|
||
|
|
||
|
// Reader that decodes a Dynamic to a list of integers
|
||
|
fn int_list_reader() {
|
||
|
dynamic.list(dynamic.int)
|
||
|
}
|
||
|
|
||
|
// A writer that converts a list of integers to a Json value
|
||
|
fn int_list_writer() {
|
||
|
fn(val: List(Int)) { json.array(val, json.int) }
|
||
|
}
|
||
|
|
||
|
// First use plinth to get the low level storage
|
||
|
let assert Ok(local) = storage.local()
|
||
|
|
||
|
// Construct TypedStorage with the reader and writer
|
||
|
let s = varasto.new(local, int_list_reader(), int_list_writer())
|
||
|
|
||
|
// Set a value
|
||
|
varasto.set(s, "Foo", [1, 2, 3])
|
||
|
|
||
|
// Returns Ok([1, 2, 3])
|
||
|
varasto.get(s, "Foo")
|
||
|
```
|
||
|
|
||
|
## Installation
|
||
|
|
||
|
This package can be added to your Gleam project:
|
||
|
|
||
|
```sh
|
||
|
gleam add varasto
|
||
|
```
|
||
|
|
||
|
and its documentation can be found at <https://hexdocs.pm/varasto>.
|