Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

level-ts

Package Overview
Dependencies
Maintainers
2
Versions
25
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

level-ts

The hard typed level module with some extra features

  • 2.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.3K
decreased by-25.04%
Maintainers
2
Weekly downloads
 
Created
Source

npm Gitlab pipeline status (self-hosted) coverage

DevDroplets

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:

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:

db.get('b', (error, data) => {
  if(error) throw error;
  console.log(data);
});

In this package and forcefully applied:

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:

// 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:

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 or Sublevel. This allows for some more customization and useability.

Typescript support
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.

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.

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

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:

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.

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 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.

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.

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 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.

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 method! Highly recommended for readability and performance.

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 for giving the iterator idea!)

Iterate filter

Works exactly as Array.filter( ... ) but with the database values as array. Preferr

const data = await db.iterateFilter((value, key) => { return !!value.isCool }); // Returns all the objects that are cool
Iterate find

Works almost like Array.find( ... ).

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:

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...

Keywords

FAQs

Package last updated on 27 Aug 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc