# level-ts

> The hard typed level module with some extra features

Latest version **2.1.0** (published 2021-08-27) · MIT license · 0 weekly downloads

## Install

```sh
npm install level-ts
pnpm add level-ts
yarn add level-ts
bun add level-ts
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.1.0 |
| Published | 2021-08-27 |
| First published | 2019-08-17 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 116.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Ryan |
| Maintainers | ferrisk, notryan |
| Keywords | typescript, typing, types, level, leveldb, database, store, storage, json, key-value |

## Links

- npm: https://www.npmjs.com/package/level-ts
- Repository: https://gitlab.com/NotRyan_/level-ts
- npm.io page: https://npm.io/package/level-ts

## Dependencies (2)

- [level](https://npm.io/package/level.md) ^5.0.1
- [levelgraph](https://npm.io/package/levelgraph.md) ^2.1.1

## Alternatives

- [@mapbox/jsonlint-lines-primitives](https://npm.io/package/@mapbox/jsonlint-lines-primitives.md) — 5.3M weekly downloads
- [reftools](https://npm.io/package/reftools.md) — 3.5M weekly downloads
- [@hey-api/openapi-ts](https://npm.io/package/@hey-api/openapi-ts.md) — 3.5M weekly downloads
- [@mapbox/geojson-rewind](https://npm.io/package/@mapbox/geojson-rewind.md) — 2.4M weekly downloads
- [turbo-stream](https://npm.io/package/turbo-stream.md) — 1.7M weekly downloads

## Recent versions

- 2.1.0 (latest) — 2021-08-27
- 2.0.6 — 2020-12-06
- 2.0.5 — 2020-07-29
- 2.0.4 — 2020-07-29
- 2.0.3 — 2020-07-15
- 2.0.2 — 2020-07-15
- 2.0.1 — 2020-07-14
- 2.0.0 — 2020-07-14
- 1.13.1 — 2020-07-10
- 1.12.2 — 2020-01-09
- 1.11.0 — 2019-10-09
- 1.10.0 — 2019-09-26
- 1.9.0 — 2019-08-28
- 1.8.3 — 2019-08-21
- 1.8.2 — 2019-08-20
- … 10 more at https://npm.io/package/level-ts/versions

## README

<div align="center">

![npm](https://img.shields.io/npm/v/level-ts?label=Version)  ![Gitlab pipeline status (self-hosted)](https://img.shields.io/gitlab/pipeline/ryan/level?gitlab_url=https%3A%2F%2Fgit.devdroplets.com) ![coverage](https://git.devdroplets.com/ryan/level/badges/master/coverage.svg)

![DevDroplets](https://img.shields.io/badge/DevDroplets-Sponsored-%23555555?style=for-the-badge&labelColor=5D64EE&link=https://blog.devdroplets.com&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOEAYAAABP2PGSAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAhAAAAIQBMKsdJQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAGdSURBVDhPrZM9TiNBEIWr2yMLMeQQcga4AgEXQGQkXIaICJEhJI5Aikh8AEJETEJAAjKemfrpfhu0WjbltdZe+JIavarqN1UzTbQhqqqqR0d9LyJydubzvwYAAFtbIqopPT9Pp8MgMp0WfWfH1/+YYnR5WSLw9TUMIjU+Pvr6/6as8Pi4GOVcDbtuGFSBz8+uYwa6jtns9NT3r01Z1e4us2pKb2/VqMa+ZzabG5YVz2b/WnH0QkXEDLi9DYGIaG/P52MsmUrOOQPb27MZs+r9/WJukW9NRPO/ECCK8eHB5z0iKaVElFLOwFxvGmA8Pjxs27YN4emp6ksTAkCM5+deX0XTxBiXTiEiilH16sqrjReIQiA6OPDqKmIMIQSi8bhpRiMioE4aQgj7+6582bB8mbZdXM86jEbFuDwREQFEZt+r/rJSMwB4ffX6puRMBLy8eH3JMGeinO/ugE1nLNS+EICUbm58fiV9L2J2fc0ssnjhV8VyX3NmZla9uPDnrQ0zs9nJyTComk0mwyBi9v7OrGr28VFebDKpdb7f8weJ3XlbEyacnAAAAABJRU5ErkJggg==)

</div>

# Level-ts typescript wrapper
A leveldb force promises, class, JSON and typescript implementing wrapper.
This can replace your current level database instance exactly, but with typescript returning and functions typing support:


```typescript
import level from 'level-ts';

const database = new level('./database');

(async function () {
  // Same as normal level but with JSON parsing and only promises
  await database.put('first', { foo: 'bar' });
  await database.get('first'); // { foo: 'bar' }
  await database.del('first');
})();
```
### Promise forcing
Callbacks are **not** supported in this database instance. Instead, promises are used to await the data or actions.
In the normal level package / the old way:
```typescript
db.get('b', (error, data) => {
  if(error) throw error;
  console.log(data);
});
```
In this package and forcefully applied:
```typescript
const data = await db.get('b');
console.log(data);
```
If the `error` argument in the callback is defined, the promise will be rejected with that as it's rejection error.

### Class and JSON support
For easy reading the function instance of *level* is replaced with an class that automatically parses JSONs.
You can initialize a database from anywhere in your file with the class caller as long as it has the same path/name. This allows for sharing the database class over the same process with ease. E.g:
```typescript
// File App.ts
const db = await level('./database');
await db.put('first', { value: 1 });

// File Route.ts
const samedb = await level('./database');
await samedb.get('first'); // { value: 1 }
```
It is also possible to use an already initialized database instance inside the level constructor. As long as it has the appropriate functions. E.g:
```typescript
import Level from 'level';
import LevelTypescript from 'level-ts';

const instance = Level('./database'); // You can use other packages too.

const db = new LevelTypescript(instance);

await db.put('first', { foo: bar });
```
This allows you to use other modules like: [Multilevel](https://www.npmjs.com/package/multilevel) or [Sublevel](https://www.npmjs.com/package/sublevel).
This allows for some more customization and useability.


#### Typescript support

```typescript
import level from 'level-ts';

interface IEntry { //
  foo: string;
}

const db = new level<IEntry>('./db');
// db functions will now only accept and return IEntry objects
// E.g:

await db.put('first', { foo: 'bar', wrong: 1 });
// Typescript error: 'wrong' does not exist in type 'IEntry'
```

#### Chaining
You can chain database actions with *level-ts* by using the `.chain` property. When using `.get` actions, an array will be returned with the values in the order that it was chained. At the end of the chain, the `.finish()` function returns the promise. If the `.finish()` function is not called, the javascript thread will continue without waiting.

```typescript
const data = await db.chain
  .put('first', { value: 1 })
  .put('second', { value: 2 })
  .put('third', { value: 3 })
  .del('third')
  .get('second')
  .get('first')
  .finish();
console.log(data); // [{ value: 2 }, { value: 1 }]
```

### Streaming
You can also "stream" data with promises. This works different than the *stream* of Node.js. It does use the same mechanic, but wraps it neatly inside a promise with typescript value return support.
```typescript
await db.chain
  .put('session-ryan-1', { ... })
  .put('session-ryan-2', { ... })
  .put('session-ryan-3', { ... })
  .put('session-foo-1', { ... })
  .put('session-foo-2', { ... })
  .put('session-foo-3', { ... })
  .finish();

const sessions = await db.stream({ all: 'session-ryan-' }) 
// The all option is the same as: { gte: 'session-ryan-', lte: 'session-ryan-\xff' }
// Returns everything starting with 'session-ryan-'
for(const { key, value } of sessions) {
  console.log(key,'=', value.toString()); // Returns all sessions from ryan
  // (Entries with prefixed key "session-ryan-")
}
```

### Extra functions

##### Exists
Returns if the given key exists in the database
```typescript 
await db.exists('first'); // false
await db.put('first', { ... });
await db.exists('first'); // true
```

##### Merge
Merges the database entry with the given object. Returns the newly created object:
```typescript
await db.put('first', { foo: 'bar', faa: 'abc' }); // returns: { foo: 'bar', faa: 'abc' }
await db.merge('first', { faa: 'boe' });           // returns: { foo: 'bar', faa: 'boe' }
await db.get('first');                             // returns: { foo: 'bar', faa: 'boe' }
```

##### All (values)
Returns all the values in the database using stream.
```typescript
const all = await db.all(); // [{ ... }, ...]
```
Due to streaming and promise awaiting is this *not the fastest* way to search for values or keys but the easiest. The functions that follow are all using this method to iterate the database and are also not meant for performance.
**Use [Iterate](#iterate) instead**

##### Filter
Works exactly as `Array.filter( ... )` but with the database values as array. **Prefer iterateFilter over this function** as it doesn't use `db.all` but `db.iterate` instead.
```typescript
const data = await db.filter((v, i, a) => { return !!v.isCool }); // Returns all the objects that are cool
```

##### Find
Works exactly as `Array.find( ... )` but with the database values as array. **Prefer iterateFind over this function** as it doesn't use `db.all` but `db.iterate` instead.
```typescript
const data = await db.find((v, i, a) => { return v.user === 'Ryan'}); // Finds the first object that has user value 'Ryan'
```

##### Iterate
Works like all the [async iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) out there. Just call the function and pass some stream functions, use the `.next()` callee and do not forget to `.end()` as it frees up your memory.
```typescript
const iterator = db.iterator({ all: "users::", keys: false });
iterator.seek("users::r"); // Seek user entries starting with Ryan
const firstUser = await iterator.next();
...
const secondUser = await iterator.next();
...
await iterator.end(); // Do not forget! Saves ya sum delicious memory.
```
Or you can use the [for await ... of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) method! Highly recommended for readability and performance.
```typescript
const iterator = db.iterator({ });
// ? iterator.seek(...); // You can first seek if you'd like.
for await (const { key, value } of iterator) {
  console.log(key, value); // Useable, readable and fast!
} // If the end of the iterable is reached, iterator.end() is callend.
await iterator.end(); // However, it is better to be safe than sorry.
```

(Credits to [@Beeno Tung](https://gitlab.com/beenotung) for giving the iterator idea!)

##### Iterate filter
Works exactly as `Array.filter( ... )` but with the database values as array.
Preferr 
```typescript
const data = await db.iterateFilter((value, key) => { return !!value.isCool }); // Returns all the objects that are cool
```

##### Iterate find
Works almost like `Array.find( ... )`.
```typescript
const data = await db.iterateFind((value, key) => { return value.user === 'Ryan'}); // Finds the first object that has user value 'Ryan'
```

# Levelgraph
Level graph database is also implemented inside this package like this:
```typescript
import { LevelGraph } from 'level-ts';
const graphdb = new LevelGraph('./graph-database');

await graphdb.put({ subject: 'Ryan', predicate: 'owns-a', object: 'foo' });
await graphdb.get({ subject: 'Ryan', predicate: 'owns-a' }); // [{ subject: 'Ryan', predicate: 'owns-a', object: 'foo' }]
const owns = await graphdb.find('Ryan', 'owns-a', null);
console.log(owns) // "foo"
```

Should extend...

---
_Source: https://npm.io/package/level-ts · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
