tfa-jsonmap
v1.3.0
Published
⚡ A simple, powerful, and useful database based on JSON files
Downloads
8
Maintainers
Readme
⚡ A simple, powerful, and useful JSON database, similar to Map
but with over 50+ methods and features, and the data is saved in a specific .json file.
- Beginner-Friendly.
- Simple, free, and easy to use.
- Helpful guide by using IntelliSense and in declaration files.
- Built-in Math conditions (including strict mode).
- Customizable only allowed types for property values.
- 100% written in TypeScript.
Note: It is recommended to use TypeScript for the types. You can use JavaScript but it will not care about the types, which is going to cause many errors and problems in the future.
Table of Contents
- TFA-JSONMap
- Table of Contents
- Requirements
- Installation
- What's new?
- Load a module
- Example usage
- Constructor options
- Type parameter
- Modules
- FAQs
- License
Requirements
- Node.js version 16.0.0 or above.
Installation
Install the latest version:
npm install tfa-jsonmap
Install the latest prerelease version:
npm install tfa-jsonmap@prerelease
What's new?
- New methods:
setJSON
,lock
, andunlock
. - New property:
locked
(boolean).
Load a module
TypeScript:
import { } from 'tfa-jsonmap';
JavaScript (CommonJS):
const { } = require('tfa-jsonmap');
Example usage
Define a new database using JSONMap:
import { JSONMap } from 'tfa-jsonmap';
const db = new JSONMap<any>('./path/to/your/json/file.json');
Type parameter using interface
keyword:
interface User {
name: string,
age: number,
gender?: 'Male' | 'Female', // <= Optional property
hobbies: string[]
};
const db = new JSONMap<User>('./path/to/your/json/file.json');
db.set('Micheal', {
name: 'Micheal',
age: 45,
hobbies: ['Football', 'Tennis']
});
Using simple methods:
const db = new JSONMap<string|number|string[]>('./path/to/your/json/file.json');
db.set('username', 'T.F.A');
db.set('balance', 69420);
db.set('langs', ['PY', 'TS']);
db.push('langs', 'Rust', 'JS'); // => langs: ['PY', 'TS', 'Rust', 'JS']
db.filter('langs', (item) => item !== 'Rust'); // => langs: ['PY', 'TS', 'JS']
db.has('balance'); // => true
db.delete('balance');
db.has('balance'); // => false
db.keys(); // => ['username', 'langs']
db.values(); // => ['T.F.A', ['PY', 'TS, 'JS']]
db.reverse();
db.keys(); // => ['langs', 'username']
db.values(); // => [['PY', 'TS, 'JS'], 'T.F.A']
db.keyIndex('langs'); // => 0
db.keyAt(1); // => 'username'
db.hasAll('username', 'langs'); // => true
db.hasAll('username', 'age', 'langs'); // => false
db.hasAny('username', 'langs'); // => true
db.hasAny('username', 'age', 'langs'); // => true
db.deleteMany('username', 'langs');
db.keys(); // => []
db.set('var1', 45);
db.set('var2', 45);
db.set('var3', '45');
db.set('var4', 60);
db.on('keyCreate', (key, value) => { });
db.on('keyDelete', (key) => { });
db.$equalTo('var1', 'var2'); // => true
db.$equalTo('var2', 'var3'); // => true
db.$strictEqualTo('var2', 'var3'); // => Error: TypeError
db.$lessThan('var4', 'var2'); // => false
db.$greaterThan('var4', 'var2'); // => true
db.$lessThanOrEqual('var1', 'var2'); // => true
db.$greaterThanOrEqual('var2', 'var4'); // => false
db.typeofKey('var3'); // => string
db.typeofKey('var1'); // => number
db.isRepeated(45); // => true
db.isRepeated(60); // => false
db.replace('var2', 'var4'); // => var4: 45
db.deleteMany('var2', 'var4');
db.map((K, V) => `K: ${K}; V: ${V}`); // => ['K: var1; V: 45', 'K: var3; V: 45']
db.clone<any>('new-file.json')
.then((newdb) => newdb.toJSON()); // => { 'var1': 45, 'var3': '45' }
db.toJSON(); // => { 'var1': 45, 'var3': '45' }
Constructor options
| Option | Type | Required? | Default | Description |
| ------ | ----- | ----- | ----- | ----- |
| autoclear | boolean | No | false
| Clear the data on startup? || prettier | boolean | No |
false` | Make the JSON file looks pretty? |
Type parameter
This only works for TypeScript. The types below are for keys' values. By default, it's any
. This is also applies for the method JSONMap#clone()
.
new JSONMap<string>(); // Only string is acceptable.
new JSONMap<number>(); // Only number is acceptable.
new JSONMap<boolean>(); // Only boolean is acceptable.
new JSONMap<object>(); // Only object is acceptable.
new JSONMap<[]>(); // Only array is acceptable.
new JSONMap<null>(); // Only null is acceptable.
new JSONMap<any>();// Any type is acceptable.
Modules
Class: JSONMap
- Methods: [55]
- $equalTo: Whenever the first key's value is equal to second key's value.
- $greaterThan: First key > Second key
- $greaterThanOrEqual: First key >= Second key
- $lessThan: First key < Second key
- $lessThanOrEqual: First key <= Second key
- $strictEqualTo: Whenever the first key's value is equal to second key's value, and must have same type value.
- at: Get an element from a key's value array by it's index.
- clear: Delete all the keys.
- clone: Create a new JSON file with the same data as the original one.
- delete: Delete a key.
- deleteMany: Delete multiple keys.
- emit: Event method; Emit a custom event or built-in event.
- entries: Get all the entries; keys and their value.
- fill: Replace all values with a new value.
- filter: Filter an array, it's mostly used to pull multiple elements from an array.
- firstKey: Get the first key's name from the data.
- firstValue: Get the first value from the data.
- forEach: Similar to
for
keyword. First argument is the key, second argument is the value. - get: Get a key's value.
- getMany: Get multiple keys' values in an array.
- has: Whenever the provided key exists in the data or not.
- hasAll: Whenever all the provided keys exists in the data. If one of them doesn't, even the others exist, it will return
false
. - hasAny: Whenever all the provided keys exists in the data. If one of them exist, even the others doesn't exist, it will return
true
. - isNull: Whenever the provided key is having the
null
value or not. - isRepeated: Whenever the provided value exists in two or more different key names.
- keyAt: Get a key's name by it's index from the data.
- keyIndex: Get a key's index by it's name from the data.
- keys: Get all the keys in an array.
- lastKey: Get the last key's name from the data.
- lastValue: Get the last value from the data.
- lock: Lock the map, which means that you can't overwrite the data.
- map: Similar to array
map
method. First argument is key name, second argument is key's value, third argument is the index. - on: Event method; Emits whenever something has happened. Events: keyCreate, keyDelete.
- once: Event method; Emits whenever something has happened and then stops. Events: keyCreate, keyDelete.
- off: Event method; Removes a listener from an event.
- pop: Pull the last element from an array.
- push: Push multiple elements in an array. If the original key's value is not an array, it will do nothing.
- randomKey: Random key name that exist in the data.
- randomValue: Random value name that exist in the data.
- removeAllListeners: Event method; Removes all the listeners.
- replace: Replace a key's value by another key's value.
- reverse: Reverse all the entries.
- set: Add a new key and it's value in the data.
- setJSON: Overwrites the file with new data (Dangerous method).
- shift: Pull the first element from an array.
- sortKeys: Sort keys array, similar to array
sort
method. - sortValues: Sort values array, similar to array
sort
method. - toJSON: Returns the file data.
- typeofKey: Type of key's value.
- unlock: Unlock the map, which means that you can overwrite the data again.
- unshift: Push multiple values in the first index of an array.
- values: Get all the values in an array.
- (private) write: Overwrites the file with new data.
- (private) read: Returns the file data.
- Properties: [4]
- locked: Whenever the map is locked or not.
- size: Get the total keys saved in the data.
- (read-only) path: Get the path of the JSON file.
- (read-only) (private) prettier: Whenever the option
prettier
is enabled or disabled.
Enum: Events
- KeyCreate: Whenever a new key has added into the data. First argument: key (string), second argument: value (any).
- KeyDelete: Whenever a key has been deleted from the data. First argument: key (string)
FAQs
I am getting a SyntaxError, what should I do?
If your error is same as "SyntaxError: Unexpected end of JSON input", add a new empty object into the JSON file. The file content should look like this (instead of an empty file):
{}
Unfortunately, there is no auto-fix for this problem. :(
What is prettier
in the constructor options?
It will make the JSON file looks pretty and easily readable.
Toggle enabled: (true
)
{
"username": "T.F.A",
"langs": [
"JS",
"TS",
"PY",
"Bash"
]
}
Toggle disabled: (false
)
{"username":"T.F.A","langs":["JS","TS","PY","Bash"]}
How to pull an element from an array?
Use the method filter
, it will filter the array and saves the new filtered array.
Pull some specific elements:
// Pull a string:
db.filter((item) => item !== 'string');
// Pull a number:
db.filter((item) => item !== 69420);
// Pull a boolean:
db.filter((item) => item !== false);
// Pull an object:
db.filter((item) => item['property'] !== 'value');
// Pull multiple elements (any type) at same time:
db.filter((item) => item !== 'something' && item !== true);
Pull everything except specific elements:
Same example as above, but the condition must be equal (===
) instead of not equal (!==
).
License
The MIT License
Copyright (c) 2023 T.F.A
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.