This repository has been archived by the owner on Dec 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Examples
Samuel Voeller edited this page Dec 25, 2020
·
13 revisions
Below contains an example for each adapter with the expected options and examples of accessing each part of the API.
const { MemoryAdapter } = require('k-value')
const kv = new MemoryAdapter()
const { MySQLAdapter } = require('k-value')
const kv = new MySQLAdapter({
authentication: {
host: 'ip or domain',
username: 'username',
password: 'password',
database: 'database'
},
table: `kv-table-name`
})
// You must call kv#configure() before this adapter will be usable. This is an asynchronous function. (Promise)
While supported, we recommend using the
MySQLAdapter
if you intend to handle high-volume or if your data is of large physical size, due to the nature of SQLite using synchronous access for reading and writing operations.
const { SQLiteAdapter } = require('k-value')
const kv = new SQLiteAdapter({
file: require('path').resolve(__dirname, './kv-database.sqlite3'),
table: 'kv-store'
})
// You must call kv#configure() before this adapter will be usable. This is an asynchronous function. (Promise)
The below example is consistent across all adapters and is our standardized API. The only difference is how you initialize the adapter and which class you use for each adapter type.
// Replace the MemoryAdapter and constructor with whichever Adapter you would like to use.
const { MemoryAdapter } = require('k-value')
const kv = new MemoryAdapter()
// Configure the Adapter. This is required for all persistent adapters and only needs to be called once.
await kv.configure()
// Arbitrary Complex Object
const complex = {
buffer: Buffer.from('son of a buffer'),
date: new Date(),
map: new Map([['world', 'hello'], ['hello', 'world']]),
set: new Set(['world', 'hello'])
}
await kv.clear()
/* Deletes all entries from the DB. This is destructive and cannot be reverted. */
await kv.set('example', complex)
await kv.set('random-key', 11223344)
await kv.set('delete-test', 'delete-me-pls')
/* Adds Data to the Adapter */
await kv.delete('delete-test')
console.info('deleted', await kv.has('delete-test'))
console.info('get', await kv.get('example'))
/*
get { buffer: <Buffer 73 6f 6e 20 6f 66 20 61 20 62 75 66 66 65 72>,
date: 2020-12-24T08:03:10.217Z,
map: Map { 'world' => 'hello', 'hello' => 'world' },
set: Set { 'world', 'hello' } }
*/
const s = await kv.get('example')
s.set.add('some-more-data')
await kv.set('example', s)
console.info('has', await kv.has('random-key'))
/* has true */
console.info('keys', await kv.keys())
/* keys [ 'example', 'random-key' ] */