Package Exports
- jsonjsdb
Readme
Jsonjsdb - Core Library
📖 For project overview, use cases, and limitations, see the main documentation
A client-side relational database solution for static Single Page Applications. This library enables offline data storage and querying when running applications on the local file system without server infrastructure.
Table of Contents
Installation
Install via npm:
npm install jsonjsdbOr include directly in your HTML:
<script src="/dist/Jsonjsdb.min.js"></script>Basic Example
ES6/Module Usage (Recommended)
import Jsonjsdb from "jsonjsdb"
const db = new Jsonjsdb()
await db.init()
// Get all users
const users = db.get_all("user")
console.log(users)
// Get specific user
const user = db.get("user", 123)
console.log(user)Script Tag Usage
Include the library in your HTML:
<script src="/dist/Jsonjsdb.min.js"></script>Then use it in your JavaScript:
const db = new Jsonjsdb()
db.init().then(() => {
const users = db.get_all("user")
console.log(users)
})Database structure and management
The relational database has specific structural requirements:
- By default, the database is contained in a folder named db. This folder should be located in the same directory as the HTML file (entry point).
- The database folder can be customized using the configuration parameters (see Configuration section below).
- The db folder contains tables represented by files with the .json.js extension. Each jsonjs file represents a table.
- The db folder contains a file named __table__.json.js that lists all table names.
Configuration
By default, the application uses a configuration automatically embedded in your HTML file:
<div id="jsonjsdb_config" style="display:none;"
data-app_name="dtnr"
data-path="data/db"
data-db_key="R63CYikswPqAu3uCBnsV"
>
</div>Parameters:
- data-app_name: Application identifier (keep as
"dtnr") - data-path: Path to your database folder (usually
"data/db") - data-db_key: Unique key for your data instance (generate new one if needed)
You can customize this configuration by passing the ID of the HTML div containing the configuration:
const db = new Jsonjsdb("#jsonjsdb_config")The jsonjs file
The jsonjs file begins with the JavaScript instantiation of the JSON data, typically on the first line.
jsonjs.data.my_table_name = or
jsonjs.data['my_table_name'] = Following this, typically on the second line, is the JSON data, which always represents a simple table structure with columns and rows. The data can be minified or formatted and currently supports two possible structures:
List of objects
The more readable format:
[
{
"column_1": 1,
"column_2": "row 1",
"column_3": "foo"
},
{
"column_1": 2,
"column_2": "row 2",
"column_3": "bar"
},
]List of lists
The more compact format:
[
["column_1", "column_2", "column_3"],
[1, "row 1", "foo"],
[2, "row 2", "bar"],
]Table and column naming
To implement relational database functionality, specific naming conventions are required:
- Table names and file names must be identical
- Table names should use camelCase convention
- Underscores in table names are reserved for junction tables, for example: myTable_yourTable
- The primary key must be a column named id
- Foreign keys are columns named after the foreign table with the suffix _id, for example: yourTable_id
API Reference
Constructor
new Jsonjsdb(config?)
Creates a new Jsonjsdb instance.
// Default configuration
const db = new Jsonjsdb()
// Custom configuration object
const db = new Jsonjsdb({ path: "data/db", app_name: "myapp" })
// HTML configuration selector
const db = new Jsonjsdb("#my_config")Parameters:
config(optional): Configuration object or string selector for HTML configuration element
Returns: Jsonjsdb instance
Data Loading
init(option?)
Initializes the database by loading all tables.
const db = new Jsonjsdb()
const result = await db.init()
console.log("Database initialized:", result === db) // trueParameters:
option(optional): Configuration options for initialization
Returns: Promise
load(file_path, name)
Loads a specific jsonjs file.
const data = await db.load("custom_table.json.js", "custom_table")Parameters:
file_path: Path to the jsonjs file (relative to db path)name: Name for the loaded data
Returns: Promise
Data Retrieval
get(table, id)
Gets a single row by ID from the specified table.
const user = db.get("user", 123)
console.log(user) // { id: 123, name: "John", email: "john@example.com" }Parameters:
table: Name of the tableid: ID of the row to retrieve
Returns: Object | undefined
get_all(table, foreign_table_obj?, option?)
Gets all rows from a table, optionally filtered by foreign key relationships.
// Get all users
const users = db.get_all("user")
// Get users with specific company_id
const companyUsers = db.get_all("user", { company: 5 })
// Limit results
const limitedUsers = db.get_all("user", null, { limit: 10 })Parameters:
table: Name of the tableforeign_table_obj(optional): Filter by foreign key { table_name: id_or_object }option(optional): Options object with limit property
Returns: Array of objects
get_all_childs(table, item_id)
Gets all child records recursively from a row (uses parent_id relationship).
// Get all children of category 1
const children = db.get_all_childs("category", 1)Parameters:
table: Name of the tableitem_id: ID of the parent row
Returns: Array of objects
Utility Methods
foreach(table, callback)
Applies a function to each row of the table.
db.foreach("user", (user) => {
user.full_name = `${user.first_name} ${user.last_name}`
})Parameters:
table: Name of the tablecallback: Function to apply to each row
Returns: void
table_has_id(table, id)
Checks if a table contains a specific ID.
if (db.table_has_id("user", 123)) {
console.log("User exists")
}Parameters:
table: Name of the table to checkid: ID to look for
Returns: boolean
has_nb(table, id, nb_what)
Counts how many records reference a specific ID in another table.
// Count how many posts reference user 123
const postCount = db.has_nb("user", 123, "post")
console.log(`User has ${postCount} posts`)Parameters:
table: The table name to use for foreign key (table + "_id")id: ID of the referenced itemnb_what: Table name where to count references
Returns: number
get_parents(from, id)
Gets all parent records recursively using parent_id relationship.
const parents = db.get_parents("category", 5)
console.log(parents) // Array of parent categories (from immediate parent to root)Parameters:
from: Table to get parents fromid: ID of the item to get parents for
Returns: Array of objects (in reverse order, from immediate parent to root)
get_config(id)
Gets a configuration value from the config table.
const setting = db.get_config("max_items")Parameters:
id: Configuration key
Returns: any | undefined