npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@wxn0brp/database.js

v0.0.1

Published

A simple file-based database management system with support for CRUD operations, custom queries, and graph structures.

Downloads

22

Readme

DataBase Class

The DataBase class simplifies managing data with a file-based database, providing an easy way to perform CRUD operations, caching, and custom queries.

Installation

Ensure you have Node.js installed. To install the DataBase package, run:

npm install @wxn0brp/database

Usage Example

const DataBase = require('@wxn0brp/database');

async function main() {
    // Initialize the database with a folder path and optional cache settings
    const db = new DataBase('./data');

    // Create or check a collection
    db.checkCollection('users');

    // Add a new user to the collection
    await db.add('users', { name: 'Alice', age: 30 });

    // Find users based on search criteria
    const users = await db.find('users', { age: 30 });
    console.log(users);

    // Update a user's data
    await db.update('users', { name: 'Alice' }, { age: 31 });

    // Remove a user
    await db.remove('users', { name: 'Alice' });
}

main().catch(console.error);

Methods Overview

| Method Name | Description | Parameters | Returns | | ----------- | ----------- | ---------- | ------- | | getDBs() | Retrieves the names of all available databases. | None | string[] | | checkCollection() | Ensures that a collection exists, creating it if necessary. | collection (string): Name of the collection | void | | add() | Adds data to a collection, optionally generating an ID. | collection (string), data (Object), id_gen (boolean) | Promise<Object> | | find() | Finds data entries matching a query. | collection (string), search (function/Object), options (Object) - { max, reverse } | Promise<Array<Object>> | | findOne() | Finds the first data entry matching a query. | collection (string), search (function/Object) | Promise<Object\|null> | | update() | Updates data entries matching a query. | collection (string), search (function/Object), arg (function/Object) | Promise<boolean> | | updateOne() | Updates the first data entry matching a query. | collection (string), search (function/Object), arg (function/Object) | Promise<boolean> | | remove() | Removes data entries matching a query. | collection (string), search (function/Object) | Promise<boolean> | | removeOne() | Removes the first data entry matching a query. | collection (string), search (function/Object) | Promise<boolean> | | updateOneOrAdd() | Updates one entry or adds a new one if no match is found. | collection (string), search (function/Object), arg (function/Object), add_arg (function/Object) | Promise<boolean> | | removeDb() | Removes an entire database collection from the file system. | collection (string) | void |


Querying Data

The DataBase class offers flexibility for querying collections using either an object or a function as the search parameter in methods like find, findOne, update, and remove.

Object-Based Queries

You can use the following operators to build your queries:

  • $or: Matches if at least one condition is true.

    const result = await db.find('users', {
        $or: [{ status: 'active' }, { role: 'admin' }]
    });
  • $not: Matches if the condition is false.

    const result = await db.find('users', {
        $not: { status: 'inactive' }
    });
  • $and: Combines multiple conditions, all of which must be true. Useful for complex queries involving other operators.

    const result = await db.find('users', {
        $and: [
          { age: 25 },
          { $or: [{ status: 'active' }, { status: 'away' }] }
        ]
    });
  • $set: Ensures that specified fields are present in the document.

    const result = await db.find('users', {
        $set: { name: true }
    });

Search as a Function

Alternatively, you can use a function for more dynamic queries. The function receives each document as an argument and should return true for documents that match the criteria.

const results = await db.find('users', obj => obj.age > 30);

This approach is powerful for cases where the query logic is too complex to be represented as an object.

Update Argument

When updating data, the update argument can also be either an object or a function.

Update as an Object

If you pass an object as the update argument, it will directly set the new values for the specified fields.

Example: Update with Object
// Updates the age of all users named 'Alice' to 31
await db.update('users', { name: 'Alice' }, { age: 31 });

Update as a Function

If you pass a function, it receives the current object as an argument and should return the updated object. This allows for dynamic updates based on the current state of the object.

Example: Update with Function
// Increments the age of all users named 'Alice' by 1
await db.update('users', { name: 'Alice' }, obj => {
    obj.age++;
    return obj;
});

This method is useful when you need to compute new values based on existing ones.

Other Features

Graph.js

The Graph class extends the functionality of the DataBase class to handle graph-like structures, where relationships (edges) between nodes (vertices) are stored in collections.

Methods

  • add(collection, a, b): Adds an edge between a and b in the specified collection. The nodes are sorted to ensure consistency in the storage format.

    // Adds a friendship between Alice and Bob
    await graph.add('friends', 'Alice', 'Bob');
  • remove(collection, a, b): Removes the edge between a and b.

    // Removes the friendship between Alice and Bob
    await graph.remove('friends', 'Alice', 'Bob');
  • find(collection, d): Finds all edges where d is one of the nodes.

    // Returns all friends of Alice
    const friends = await graph.find('friends', 'Alice');
  • findOne(collection, d, e): Finds the edge between d and e.

    // Returns the friendship between Alice and Bob, if it exists
    const relation = await graph.findOne('friends', 'Alice', 'Bob');

Gen.js

The gen.js file contains a utility function genId, which generates a unique identifier.

Example: Generating an ID

const id = genId();

License

This project is licensed under the MIT License. See the LICENSE file for details.