Tutorial part-2: Key-value store - basic operations
Published: 2022-12-18 21:48:40


A [key-value store](https://en.wikipedia.org/wiki/Key%E2%80%93value_database) has three basic operations: **get**, **set** and **delete**.
This makes it easy and efficient to insert, look up, update and remove data, as you only need to know the key to access the corresponding value. 
In this (part-2) tutorial we'll show how to use the simple [key-value store API](https://codehooks.io/docs/key-value-database-api) operations in serverless JavaScript functions.

Read the tutorial part-1 [here](https://dev.to/restdbjones/part-1-key-value-store-bji)

## Setting and getting values in the key-value store

Inserting (set) a new value in the key-value store requires a unique key string and an arbitrary string value.

`'key' => 'one 2 three'`

The API for setting and getting a value in the key-value store is shown in the code example below:
```js
// Connect to the key-value store
const db = await Datastore.open();
// set key-value
await db.set('mykey', 'My value');
// get value
const result = await db.get('mykey');
console.log(result);
``` 

Output from the `console.log` statement:

```bash
My value
```


> The `db.set(key, value, options={})` API has an options part > which lets you add a TTL value and a keyspace parameter. 
> This is covered more in the part-5/6 of this tutorial.


### Set a JSON value

Setting a JSON value in the key-value store is easy. Use the `JSON.stringify` function to convert your JavaScript object to a string value before inserting the value to the store. And use the `JSON.parse` function to convert it back to an Object when retrieving the value.

```js
const myObj = {
    "foo": "bar",
    "price": 42
};  
const db = await Datastore.open();
// convert JSON to string
await db.set('myjsonkey', JSON.stringify(myObj));
// get value from key
const result = await db.get('myjsonkey');
// convert back to Object
console.log(JSON.parse(result));
```

Output from the `console.log` statement:

```bash
{ foo: 'bar', price: 42 }
```

### Set a binary value

Using the Node.js `Buffer` library we can set any string or binary value into the key-value store. Converting a buffer value to a `hex` string is a perfect solution for this use case.

```js
  const db = await Datastore.open();
  // create a hex value from a Buffer
  const myBufVal = Buffer.from('Hello world!😎😎😎', 'utf-8').toString('hex');
  // set value
  await db.set('mybufkey', myBufVal);
  // get the value for key
  const hexString = await db.get('mybufkey');
  // convert hex string value back to a normal string
  const stringVal = Buffer.from(hexString, 'hex').toString();
  console.log(hexString, stringVal);
```

Output from the `console.log` statement:

```bash
48656c6c6f20776f726c6421f09f988ef09f988ef09f988e Hello world!😎😎😎
```

### Set a number value

Numbers are converted to its string representation.

```js
const db = await Datastore.open();
// set value as Integer
await db.set('mynumkey', 42);
// get value for key
const result = await db.get('mynumkey');
console.log(result, 'is of type', typeof result);
```

Output from the `console.log` statement:

```bash
42 is of type string
```

### Setting multiple values

In some use cases you'll need to insert or set multiple values to the key-value store.
JavaScript solves this task for us with the `Promise.all` function. The key-value store `set` function returns a `Promise`, hence we can create an array of `set` functions that we pass to the `Promise.all` function. The code example below shows you how we can create multiple key-value inserts in one operation.

```js
const db = await Datastore.open();
const array = [
  db.set('uno', 'one value'),
  db.set('dos', 'two value'),
  db.set('tres', 'three value')
]
const result = await Promise.all(array);
console.log(result);
```
Output from the `console.log` statement:

```bash
[ 'one value', 'two value', 'three value' ]
```

### Getting multiple values

Similar to the technique we use for setting multiple values in the key-value store, we can also get multiple values with the `Promise.all` function.

```js
const db = await Datastore.open();
const array = [
  db.get('uno'),
  db.get('dos'),
  db.get('tres')
]
const result = await Promise.all(array);
console.log(result);
```

Output from the `console.log` statement:

```bash
[ 'one value', 'two value', 'three value' ]
```


## Deleting values

Deleting values from the key-value store follows the same pattern as the `get` operation.
When deleteting a key-value pair, the value is returned if the key exists, otherwise a `null` value is returned. You can also use the `Promise.all` technique shown above for multiple delete operations. The code example below shows the basic delete operation.

```js
const db = await Datastore.open();
// delete key-value pair
const result1 = await db.del('uno');
// try to get the deleted key, should be null
const result2 = await db.get('uno');
console.log(result1, result2);
```

Output from the `console.log` statement:

```bash
uno null
```

This part-2 of the key-value store tutorial has shown how you can use the basic operations in serverless JavaScript functions with codehooks.io.

The next [Part-3: Increment end decrement](https://codehooks.io/docs/tutorials/key-val-store/part-3-increment-and-decrement-operations).