litejsondb v1.0.5
๐ LiteJsonDB Documentation
LiteJsonDB is a lightweight local JSON database for Node.js, designed to simplify JSON data management in your projects. This package is a fork of the Python LiteJsonDB project, adapted for Node.js. Currently, this project is about 45% complete, meaning it's already super functional but still has room for more cool features.
LiteJsonDB is like a nifty little vault for your JSON data. It provides a simple and intuitive API for adding, modifying, retrieving, and deleting data. You don't need to worry about the complexities of heavier database systems. With LiteJsonDB, you can focus on what really matters: your data.
๐ Table of Contents
๐ง Installation
To get started with LiteJsonDB, you need to install it via npm. It's super easy! Just run the following command in your terminal:
๐ฏ Usage
๐ Initialization
Once installed, you can import JsonDB
and initialize your database like this:
Options Description:
filename
: (Optional) Astring
representing the name of the JSON file used for storing the database. If no filename is provided, the default name isdatabase.json
is used. The file is located indatabase
directory.crypted
: (Optional) Aboolean
indicating whether the database should be encrypted or not. Default tofalse
.encryptionMethod
: (Optional) Astring
representing the method used for encryption, can bebase64
orcrypto
. Ifcrypted
istrue
and you don't provide an encryption method, the default will be 'base64'.secretKey
: (Optional) Astring
representing the secret key used for encryption. Required ifcrypted
istrue
andencryptionMethod
is set tocrypto
. Must be a 32-byte string.enableLog
: (Optional) Aboolean
indicating whether to log database operations. Default totrue
. Logs are saved indatabase/LiteJsonDb.log
.autoBackup
: (Optional) Aboolean
indicating if auto backup is enabled. Default tofalse
.
๐ฅ Adding Data
Adding data is a breeze with LiteJsonDB. Use the setData
method to store information in the database:
Explanation:
- Key/Value Storage: Use the
setData(key, value)
method to store your data in the database. The data is stored as a JSON object. - Data Format: The
value
must be anobject
, other types are not supported. - Key Structure: The
key
is a string representing the path for the new entry. The path is created recursively if it does not exist. If thekey
already exists, the data is not added, you should useeditData
to modify it.
๐ Editing Data
To update existing data, use editData
. You can modify information without erasing whatโs already there:
Explanation:
- Merging Objects: The
editData(key, value)
method merges existing data at the given path with the new data you provide. - Key Path: The
key
is a string representing the path for the entry to be edited. - Value Format: The
value
must be an object. Non-object types are not supported. - Key Check: If the
key
doesn't exists an error will be returned. You should usesetData
to create a new entry.
๐ Getting Data
The getData
method allows you to retrieve data from the database. You can specify the exact path of the data you want to access. Hereโs how you can use it:
Explanation:
- Path Specification: You use a key path like
'users/1'
or'products/1'
to retrieve specific entries from the database. The key path is a string that denotes the location of the data in the hierarchical structure of the database. - Default Behavior: If the specified path does not exist,
getData
will returnnull
. Ensure you handle such cases in your code to avoid errors. - Data Format: The returned data will be the value of the key or subcollection.
โ Deleting Data
Need to delete data? No problem! The deleteData
method allows you to remove specific information. You have two options:
Delete Specific Entry: If you want to delete a specific entry, provide the exact key path:
This command will remove only the data located at
'products/1'
, leaving other data intact.Delete All Data Under a Path: If you want to delete all data under a specific key path, you can use a nested key path:
This will remove the entire
'products'
section, including all entries within it, such as'products/1'
and any other nested products.
Explanation:
- Specific Entry Deletion: By providing a precise path like
'products/1'
, you delete only that particular entry. - Path-Wide Deletion: Using a broader path like
'products'
deletes everything under that path. This is useful for clearing out all related data but should be used carefully to avoid unintentional data loss. - Key Check: An error is returned if the specified path does not exist.
๐ Searching Data
You can also search your data with searchData
. This helps you find specific values anywhere in the database:
Explanation:
- Search Value: The
searchData(data, searchValue, key)
searches for thesearchValue
in thedata
. - Data: The first parameter
data
is the dataset to be searched,db.showDb()
for the entire database ordb.getData('your/path')
for a specific data part. - Key: The third parameter
key
is optional, if provided the search will be done only in the given path. - Return: The method will return the matching values in
object
with the path as the key. - Not Found: If no matches found an error will be displayed.
๐ฆ Managing Subcollections
You can use setSubcollection
, editSubcollection
and getSubcollection
methods to handle nested objects
setSubcollection(parentKey, subcollectionKey, subcollectionData)
: This allows you to add or update a sub-collection within a specified parent keyeditSubcollection(parentKey, subcollectionKey, subcollectionData)
: This allows you to update an existing sub-collection within a specified parent keygetSubcollection(parentKey, subcollectionKey)
: You can use this to retrieve either the entire subcollection or a specific part of itdeleteSubcollection(parentKey, subcollectionKey)
: Use this method to remove a specific sub-collection.
๐พ Backup and Restore
LiteJsonDB provides functions for backing up and restoring the database:
backupDb(backupFile)
: Creates a backup of the database to the specifiedbackupFile
in thedatabase
directory.restoreDb(backupFile)
: Restores the database from the specifiedbackupFile
.
๐ก๏ธ Regex Validation
You can use setRegex
to set a regex for the value of an entry and validateData
to check if the values respect the regex that is previously set using setRegex
:
setRegex(key, regexPattern)
: Allows you to define a regex pattern for a value of givenkey
validateData(data)
: Allows you to check if the data is valid according to the defined regex.- If a value does not respect the regex pattern an error will be returned.
โจ Additional Features
showDb()
: Returns the entire database object.convertToDateTime(key)
: Converts a timestamp to a date time string.- If the
key
doesn't exists or isn't valid anull
value will be returned.
- If the
flattenJson(key)
: Flattens a nested JSON object to a one-level object- If
key
is empty, it will flatten the entire database - If the
key
doesn't exists or isn't valid anull
value will be returned.
- If
keyExists(key)
: Used to check if the key exists or not
๐ ๏ธ Utility Functions
LiteJsonDB includes some handy utility functions:
hashPassword(password)
: Hashes the given password using SHA256.checkPassword(storedHash, password)
: Checks if the given password matches the stored hash.getOrDefault(data, key, defaultValue)
: Returns the value for the key if it exists in thedata
, or thedefaultValue
if the key doesn't exist.keyExistsOrAdd(data, key, defaultValue)
: Checks if the givenkey
exists in thedata
and returnstrue
. If not, it adds the key with the specifieddefaultValue
and returnsfalse
.searchData(data, searchValue, key)
: Searches for thesearchValue
in the provideddata
, and return the matches if it found. Thekey
is optional, if it's provided the search will be done only in the given pathsanitizeOutput(data)
: Returns a stringified JSON with a pretty print format.prettyPrint(data)
: Prints a pretty format of the JSON object.
Hereโs how you can use them:
๐ Example Code
Hereโs a small example to show you how everything works together:
๐ ๏ธ Future Development
LiteJsonDB is a fork of our Python LiteJsonDB package. Iโve managed to reproduce about 45% of the work so far, and it's already functional with features like adding, editing, and deleting data. However, thereโs still a lot to be done!
If you have skills in both Node.js and Python, you might want to dive into the code and contribute to the Node.js project. Currently, Iโm focused more on Python development and may not have enough time to add all the desired features to this package.
Your contributions could help move the project forward and make it even better. Feel free to explore the code and get involved!
๐ฌ Contribution
If you want to contribute to the project, feel free to open issues or pull requests. Every contribution is welcome to help make this project even better!