Skip to content

Latest commit

 

History

History
237 lines (172 loc) · 3.75 KB

driver-memory.md

File metadata and controls

237 lines (172 loc) · 3.75 KB

Memory-based Storage (Default)

On this page, you can find examples of using the memory-based driver.

Table of Contents

Usage

This is the default diver of the storage-box package, No further configuration is required.

import { Client } from 'storage-box';

const c = new Client();

Key/Value Operations

set
client.set('key', 'value');
get
const value = client.get('key');
getall
const objs = client.getall();
delete
client.del('key');
clear
client.clear();
exists
const exists = client.exists('key');
const has = client.has('key'); // has is an alias for exists
size

Length of the storage

const size = client.size();
keys
const keys = client.keys();
values
const values = client.values();

Time-based Key Expiration

Setex
client.setex('key', 'value', 10); // 10 seconds
TTL

Returns the remaining time in seconds

const ttl = client.ttl('key');
const ttlMs = client.ttl('key', true); // Returns the remaining time in milliseconds

Hash Operations

createHashMap

interface Vertex {
  x: number;
  y: number;
}

const hash = client.createHashMap<string, Vertex>();

Abstract HashMap

import { expect } from 'chai';
import type { JsonObject } from 'storage-box';

interface CuteUser extends JsonObject {
  first: string;
  last: string;
}

class CuteMap extends HashMap<string, CuteUser> {
  async addUser(user: CuteUser) {
    const randId = Math.random().toString(36).slice(2);
    await this.set(randId, user);
  }

  async initials(): string[] {
    const all = await this.getall();
    return Object.values(all).map((u) => `${u.first[0]}${u.last[0]}`);
  }
}

const cuties = client.createHashMap(CuteMap);

await cuties.addUser({ first: 'Mary', last: 'Jane' });
await cuties.addUser({ first: 'Peter', last: 'Parker' });

const initials = await cuties.initials();
expect(initials).to.have.members(['MJ', 'PP']);

hset

client.hset('key', 'field', 'value');

hget

const value = client.hget('key', 'field');

hgetall

const map = client.hgetall('key');

hsetex

client.hsetex('key', 'field', 'value', 10); // 10 seconds

hkeys

const keys = client.hkeys('key');

hvalues

const values = client.hvalues('key');

hdel

client.hdel('key', 'field');

hexists

const exists = client.hexists('key', 'field');

hsize

const size = client.hsize('key');

hclear

client.hclear('key');