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

0db

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

0db

Simple JSON file database.

  • 0.0.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Weekly downloads
 
Created
Source

🚧 Work in progress...

⭕ 0db

NPM version

Simple JSON file based database with easy querying interface and common utilities.

For whatever reason, If you don't want to use a real database, and instead simply use a file. but also want some query and utility functions of a database. this is 0db 😁.

👇 Glimpse example :

db("users").create({ name: "kenza", email: "kenza@old.com" });
db("users").read({ name: "kenza" });
db("users").update({ name: "kenza" }, { email: "kenza@new.com" });
db("users").delete({ name: "kenza" });

0db is constituted of four (create, read, update, and delete) methods that represents the CRUD operations and three (or less) parameters (item, query, and options) considerably (more or less) recurring in the four methods.

📥 Installation

npm i 0db

🏁 Getting Started

👇 Learn by a simple common example :

// Require library
const $0db = require("0db");

// Initialize database
// 💡 By default, A "db.json" file will be created in root directory
const db = await $0db();

// Create a new item within a collection named "users"
// 💡 If the collection doesn't exist it will be created automatically
// 💡 With the utility option "encrypt", the "password" field
//    will be saved as an encrypted hash string instead of the original
const createdUser = await db("users").create(
  {
    name: "kenza",
    email: "kenza@email.com",
    password: "secret123",
  },
  {
    encrypt: "password",
  }
);

// Read all items from "users" collection where "name" is "kenza"
// 💡 The "omit" option hides the "password" and "email"
//    fields in the returned results
const users = await db("users").read(
  { name: "kenza" },
  {
    omit: ["password", "email"],
  }
);

// Update all "users" items where "name" is "kenza"
// with new values for "email" and "password"
const updatedUser = await db("users").update(
  { name: "kenza" },
  {
    email: "kenza@NewEmail.com",
    password: "NEW_SECRET_123456789",
  }
);

// Delete all "users" items where "email" is "kenza@NewEmail.com"
const deletedUser = await db("users").update({ email: "kenza@NewEmail.com" });

💡 A JSON file named db.json (by default) is created in the root directory. This is an example of its content :

{
  "users": [
    {
      "name": "kenza",
      "email": "kenza@example.com",
      "$id": "8c8f128e-4905-4e77-b664-e03f6de5e952",
      "$createdAt": "2021-09-05T21:40:27Z"
    },
    {
      "name": "ambratolm",
      "email": "ambratolm@example.com",
      "$id": "5211133c-a183-4c99-90ab-f857adf5442a",
      "$createdAt": "2002-11-01T22:12:55Z",
      "$updatedAt": "2021-10-02T00:00:00Z"
    }
  ]
}

💡 Note that the $id and $createdAt fields are created automatically when an item is created, and $updatedAt when it is updated.

🚩 Initialize

// Initialize with a "db.json" file in the root directory
const db = await fsdb();

// Initialize with a custom named JSON file in the root directory
const db = await fsdb("my-database-file.json");

// Initialize with a custom named JSON file in the current directory
const db = await fsdb(__dirname + "/my-database-file");

🔎 Query

Query parameter in Read, Update, and Delete methods is an object or function that allows targeting specific items in collection.

  • Query object :
{
  fieldName: fieldValue,
  fieldName: fieldValue,
  ...etc
}

Query object is an object of property values to match against collection items.
A comparison is performed between every item object property values in collection and the query object property values to determine if an item object contains equivalences.
The items containing the equivalences are returned.

Example:

const queryObj = {
  firstName: "kenza",
  age: 20,
  rating: 5
};

const users = await db("users").read(queryObj);
  • Query function :
(item, index?, collection?) => [Boolean]

Query function is a predicate called for every item when iterating over items of collection.
All items predicate returns truthy for are returned.
The predicate is invoked with three arguments :

  • value : Required. The value of the current item.
  • index : Optional. The index of the current item in collection.
  • collection : Optional. The collection array-object the current item belongs to.

Example:

const queryFn = (user) => {
  return user.name.startsWith("k") && user.age >= 20 && rating >= 5;
};

const users = await db("users").read(queryFn);

☑️ Options

{
  optionName: optionValue,
  optionName: optionValue,
  ...etc
}

Options parameter in all methods is an object that allows to apply additional stuff to the method's subject item or to the method's returned items result.
Every method can have specific options or common options depending on the context of the method.

Example :

const options = {
  unique: ["name", "email"],
  encrypt: "password",
  omit: ["email", "password"],
  nocase: true
};

const user = {
  name: "moulay-elhassan",
  email: "hasson@example.com",
  password: "secret#hasson?1980"
}

const createdUser = await db("users").create(user, options);

💠 CREATE

await db(collectionName).create(item?, options?);

Creates a new item in a collection.
💡 If the specified collection doesn't exist it will be created automatically.
💡 If no item object is specified (omitted, null, or undefined), an empty item is created with no fields except the system fields (with names starting with $ sign).
💡 The created item is returned.

ParameterTypeDefaultDescription
collectionNameStringTargeted collection name
itemObject{}Item to create
optionsObject{}CREATE options
@returnsObjectThe created item
@throwsErrorIf a unique field value is already used
@throwsErrorIf a value to encrypt is not a string

☑️ CREATE Options

PropertyTypeDefaultDescription
uniqueString or String[]""Fields to declare as unique
encryptString or String[]""Fields to encrypt
pickString or String[]""Fields to pick in returned items
omitString or String[]""Fields to omit in returned items
nocaseBooleanfalseIf true ignores case in search

💡 When fields are declared as unique, a checking for duplicates is done before adding the item.

💡 If nocase is true, letter case comparison will be ignored in search operations, like for example checking unique values.

🎯 CREATE Examples

// Create an item within a collection named "players" (automatically created)
// The created item is returned
const createdPlayer = await db("players").create({
  name: "ambratolm",
  level: 99,
  inventory: ["sword", "shield", "potion"],
});

// Create an item within a collection named "players" with some options
const createdPlayer = await db("players").create(
  {
    name: "ambratolm",
    level: 99,
    inventory: ["sword", "shield", "potion"],
    password: "this_is_a_secret",
  },
  {
    // Options
    unique: "name", // Make "name" field unique
    encrypt: "password", // Encrypt "password" field
    omit: ["password", "level"], // Omit fields in the returned item object
    nocase: true, // Ignore case when comparing strings
  }
);

💠 READ

await db(collectionName).read(query?, options?);

Reads an existing item in a collection.
💡 If the specified collection doesn't exist it will be created automatically.
💡 If no query is specified (omitted, null, or undefined), the query defaults to empty query {} which returns all items.
💡 The read items are returned.

ParameterTypeDefaultDescription
collectionNameStringTargeted collection name
queryObject{}Query object or function
optionsObject{}READ options
@returnsArrayThe read item
@throwsErrorIf an encrypted field not matched

☑️ READ Options

PropertyTypeDefaultDescription
oneBooleanfalseReturn only one result (Object)
pickString or String[][]Fields to pick in returned items
omitString or String[][]Fields to omit in returned items
nocaseBooleanfalseIgnore case in search
sortString or String[]""Fields to sort by returned items
orderString or String[]"asc"Order of sorting of returned items
encryptString or String[][]Fields to encrypt
limitNumberMAXNumber of returned items
pageNumber0Index of pagination (with limit)
expandString""Name of collection to expand to
embedString""Name of collection to embed

🎯 READ Examples

// Read all items in "players" collection
const players = await db("players").read();

// Read items matching a query object
const somePlayers = await db("players").read({ name: "ambratolm" });

// Read items matching a query function
const someOtherPlayers = await db("players").read(
  (player) => player.level >= 90
);

// Read items matching a query with some options
const player = await db("players").read(
  { name: "AmBrAtOlM" },
  {
    // Options
    nocase: true, // Ignore case when comparing strings
    one: true, // return only one result (an object instead of array)
  }
);

💠 UPDATE

await db(collectionName).update(query?, changes?, options?);

Updates an existing item in a collection.
💡 If the specified collection doesn't exist it will be created automatically.
💡 If no query is specified (omitted, null, or undefined), no item is updated.
💡 If an empty query {} is specified, all items are updated. 💡 If no changes are specified (omitted, null, or undefined), the changes default to empty changes {} which only updates the $updatedAt field in targeted items. 💡 The updated items are returned.

ParameterTypeDefaultDescription
collectionNameStringTargeted collection
queryObject{}Query object or function
changesObject{}Changes to apply
optionsObject{}Additional options
@returnsArrayThe updated item
@throwsErrorIf Items matching query not found
@throwsErrorIf a unique field value is already used
@throwsErrorIf a value to encrypt is not a string

☑️ UPDATE Options

PropertyTypeDefaultDescription
totalBooleanfalseIf true overrides all item fields
oneBooleanfalseReturn only one result (Object)
uniqueString or String[]""Fields to declare as unique
encryptString or String[][]Fields to encrypt
pickString or String[][]Fields to pick in returned items
omitString or String[][]Fields to omit in returned items
nocaseBooleanfalseIgnore case in search

🎯 UPDATE Examples

// Update item(s)
// The updated item is returned
const updatedPlayer = await db("players").update(
  { name: "ambratolm" }, // Query can also be a function
  { name: "new name", level: 0 } // Changes to apply
);

// Update item(s) with some options
const updatedPlayer = await db("players").update(
  { name: "ambratolm" }, // Query can also be a function
  { name: "new name", level: 0 }, // Changes to apply
  {
    // Options
  }
);

💠 DELETE

await db(collectionName).delete(query?, options?);

Deletes an existing item in a collection.
💡 If the specified collection doesn't exist it will be created automatically.
💡 If no query is specified (omitted, null, or undefined), no item is deleted.
💡 If an empty query {} is specified, all items are deleted.
💡 The deleted items are returned.

ParameterTypeDefaultDescription
collectionNameStringTargeted collection name
queryObject{}Query object or function
optionsObject{}Additional options
@returnsObjectThe deleted item
@throwsErrorIf Items matching query not found

☑️ DELETE Options

PropertyTypeDefaultDescription
oneBooleanfalseReturn only one result (Object)
pickString or String[][]Fields to pick in returned items
omitString or String[][]Fields to omit in returned items
nocaseBooleanfalseIgnore case in search

🎯 DELETE Examples

// Delete item(s)
// The deleted item is returned
const deletedPlayer = await db("players").delete(
  { name: "ambratolm" } // Query can also be a function
);

// Delete item(s) with some options
const deletedPlayer = await db("players").delete(
  { name: "ambratolm" }, // Query can also be a function
  {
    // Options
  }
);

↘️ Other

// Remove all collections
await db.drop();

// Remove a collection named "players"
await db("players").drop();

// Remove all items in a collection named "players" and keep it
await db("players").clear();

📃 License

MIT © Ambratolm

Keywords

FAQs

Package last updated on 04 Oct 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