### Install Development Utilities
Source: https://github.com/typicaljoe/taffydb/blob/master/README.md
Shows the command to run the `install_dev.sh` script, which installs development utilities like jslint, nodeunit, and uglifyjs. These are necessary for contributing to TaffyDB development.
```bash
./install_dev.sh
```
--------------------------------
### TaffyDB Query Examples
Source: https://github.com/typicaljoe/taffydb/blob/master/README.md
Illustrates various query methods in TaffyDB for filtering and retrieving data. Includes examples for equality, less than, like, first, and last record retrieval.
```javascript
// where item is equal to 1
var item1 = products({item:1});
// where price is less than 100
var lowPricedItems = products({price:{lt:100}});
// where name is like "Blue Ray"
var blueRayPlayers = products({name:{like:"Blue Ray"}});
// get first record
products().first();
// get last record
products().last();
```
--------------------------------
### Install and Require TaffyDB in Node.js
Source: https://github.com/typicaljoe/taffydb/blob/master/README.md
Provides instructions on how to install TaffyDB using npm and how to require it in a Node.js application. This enables server-side usage of the library.
```bash
$ npm install --production taffy
# and then in your code
TAFFY = require( 'taffy' ).taffy;
```
--------------------------------
### Sort TaffyDB Data and Get First Record (JavaScript)
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/beginner.html
This snippet demonstrates initializing TaffyDB with data, inserting a new record, sorting the data by 'name' using the .order() method, and then retrieving the name of the first record in the sorted collection. It requires the TaffyDB library to be included.
```javascript
var cities = TAFFY([{name:"New York",state:"WA"},{name:"Las Vegas",state:"NV"},{name:"Boston",state:"MA"}]);
cities.insert({name:"Portland",state:"OR"});
alert(cities().order("name").first().name);
```
--------------------------------
### Query TaffyDB and Count Results
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/beginner.html
This example shows how to query a TaffyDB database for specific records using a filter object. It then uses the .count() method to return the number of matching records, demonstrating a basic query operation.
```javascript
var cities = TAFFY([{name:"New York",state:"WA"},{name:"Las Vegas",state:"NV"},{name:"Boston",state:"MA"}]);
cities.insert({name:"Portland",state:"OR"});
alert(cities({name:"Boston"}).count());
```
--------------------------------
### Create a TaffyDB Database Instance
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/beginner.html
This code demonstrates how to create an empty TaffyDB database instance named 'cities' using the TAFFY() constructor. This is the initial step before adding any data.
```javascript
var cities = TAFFY();
```
--------------------------------
### Paginate Results in TaffyDB (JavaScript)
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Demonstrates how to paginate through TaffyDB results using the `limit()` and `start()` methods. `limit()` specifies the maximum number of records to return, while `start()` sets the offset for the results. These methods are useful for implementing features like page navigation.
```javascript
var articles = TAFFY([
{ id: 1, title: "Article 1" },
{ id: 2, title: "Article 2" },
{ id: 3, title: "Article 3" },
{ id: 4, title: "Article 4" },
{ id: 5, title: "Article 5" }
]);
// Get first 3 records
var firstPage = articles().limit(3).get();
console.log(firstPage.length); // Output: 3
// Get records starting from position 3
var fromThird = articles().start(3).get();
console.log(fromThird.length); // Output: 3 (records 3, 4, 5)
// Pagination: page 2 with 2 items per page
var page2 = articles().start(3).limit(2).get();
console.log(page2.map(r => r.id)); // Output: [3, 4]
```
--------------------------------
### TaffyDB Record Manipulation Examples
Source: https://github.com/typicaljoe/taffydb/blob/master/README.md
Shows how to perform record manipulation operations in TaffyDB, including updating records, iterating over records, sorting, selecting specific fields, and using string templating.
```javascript
// update the price of the Blue Ray Player to 89.99
products({item:1}).update({price:89.99});
// loop over the records and call a function
products().each(function (r) {alert(r.name)});
// sort the records by price descending
products.sort("price desc");
// select only the item names into an array
products().select("name"); // returns ["3D TV","Blue Ray Player"]
// Inject values from a record into a string template.
// Row value will be set to "
| 3D TV | 17999.99 |
"
var row = products({item:2})
.supplant("| {name} | {price} |
");
```
--------------------------------
### Chain TaffyDB Methods for Iteration
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/beginner.html
This code demonstrates chaining TaffyDB methods to retrieve and process data. It limits the results to the first two records and then uses the .each() method to iterate and display the 'name' property of each record.
```javascript
var cities = TAFFY([{name:"New York",state:"WA"},{name:"Las Vegas",state:"NV"},{name:"Boston",state:"MA"}]);
cities.insert({name:"Portland",state:"OR"});
cities().limit(2).each(function (r) {alert(r.name)});
```
--------------------------------
### Run TaffyDB Regression Tests
Source: https://github.com/typicaljoe/taffydb/blob/master/README.md
Details the steps to run the TaffyDB regression test suite using nodeunit. This involves navigating to the taffydb directory, installing dev dependencies, and executing the test script.
```bash
cd taffydb
./install_dev.sh # as above
bin/nodeunit ./nodeunit_suite.js
```
--------------------------------
### Include TaffyDB in HTML
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/beginner.html
This snippet shows how to include the TaffyDB library in an HTML file using a script tag. It assumes the TaffyDB JavaScript file is accessible via a URL.
```html
```
--------------------------------
### Retrieve All Matching Records with Get in TaffyDB
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Retrieves all records that match the current TaffyDB query. This is the preferred method for extracting data and is also used for exporting records.
```javascript
db().get(); // returns an array of all matching records
```
--------------------------------
### Add Records to TaffyDB
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/beginner.html
This snippet illustrates two ways to add records to a TaffyDB database: initializing with an array of records and using the .insert() method for individual records. It shows adding multiple records at once and then a single record.
```javascript
var cities = TAFFY([{name:"New York",state:"WA"},{name:"Las Vegas",state:"NV"},{name:"Boston",state:"MA"}]);
cities.insert({name:"Portland",state:"OR"});
```
--------------------------------
### Insert Records at Start or End of DB in TaffyDB
Source: https://github.com/typicaljoe/taffydb/wiki/Suggestions-and-New-Feature-Ideas
TaffyDB's `insert()` method allows appending records to the start of the database array by passing `true` as the last argument. This provides control over the order of data insertion.
```javascript
db.insert(records, true);
```
--------------------------------
### Count Records in TaffyDB (JavaScript)
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Demonstrates the `count()` method in TaffyDB, which returns the number of records that match a given query. Examples include counting all records, counting records that meet a simple filter, and counting records that satisfy a more complex filter condition.
```javascript
var orders = TAFFY([
{ id: 1, status: "shipped", total: 150 },
{ id: 2, status: "pending", total: 200 },
{ id: 3, status: "shipped", total: 75 },
{ id: 4, status: "cancelled", total: 300 }
]);
// Count all records
console.log(orders().count()); // Output: 4
// Count with filter
console.log(orders({ status: "shipped" }).count()); // Output: 2
// Count with complex filter
console.log(orders({ status: ["shipped", "pending"] }).count()); // Output: 3
```
--------------------------------
### Set Query Offset in TaffyDB
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Sets the starting record number for TaffyDB query results, commonly used for pagination and offsetting. It takes a single numeric argument.
```javascript
db().start(15); // Starts returning results at record 15
```
--------------------------------
### Update Records in TaffyDB
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/beginner.html
This snippet shows how to update existing records in a TaffyDB database. It first finds records matching a specific criterion (e.g., name 'New York') and then uses the .update() method to change a field (state to 'NY'). It also demonstrates retrieving a specific updated record.
```javascript
var cities = TAFFY([{name:"New York",state:"WA"},{name:"Las Vegas",state:"NV"},{name:"Boston",state:"MA"}]);
cities.insert({name:"Portland",state:"OR"});
cities({name:"New York"}).update({state:"NY"});
alert(cities({name:"New York"}).first().state);
```
--------------------------------
### TaffyDB: Create and Query Database
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/writing_queries.html
Demonstrates the basic creation of a TaffyDB database and how to run a query to retrieve all records. It also shows how to remove all records from the database.
```javascript
// Create a new empty database
var db = TAFFY();
// Run a query against the DB to return all rows
db();
// Real world example - remove all records
db().remove();
```
--------------------------------
### Create a TaffyDB Database
Source: https://github.com/typicaljoe/taffydb/blob/master/README.md
Demonstrates how to initialize a TaffyDB database by passing a JSON array of records to the TAFFY constructor. This sets up the in-memory data store.
```javascript
var product_db = TAFFY([
{ "item" : 1,
"name" : "Blue Ray Player",
"price" : 99.99
},
{ "item" : 2,
"name" : "3D TV",
"price" : 1799.99
}
]);
```
--------------------------------
### Creating a TaffyDB Database
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Demonstrates various ways to create a new TaffyDB database, including empty, with a single object, an array of objects, or a JSON string.
```APIDOC
## Creating a TaffyDB Database
### Description
You use the global TAFFY function to create a new database.
### Method
`TAFFY(data)`
### Parameters
#### Request Body
- **data** (Object | Array | String) - Required - The initial data for the database. Can be an object, an array of objects, or a JSON string.
### Request Example
// Create a new empty database
```javascript
var db = TAFFY();
```
// Create a new database with a single object (first record)
```javascript
var db = TAFFY({record:1,text:"example"});
```
// Create a new database using an array
```javascript
var db = TAFFY([{"record":1,"text":"example"}]);
```
// Create a new database using a JSON string
```javascript
var db = TAFFY('[{"record":1,"text":"example"}]');
```
### Response
#### Success Response (200)
- **db** (Object) - The newly created TaffyDB database instance.
#### Response Example
```json
{
"db": "TaffyDB Instance"
}
```
```
--------------------------------
### Create TaffyDB Database
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Demonstrates creating a new TaffyDB database. Supports creating an empty database, with a single object, an array of objects, or a JSON string.
```javascript
var db = TAFFY();
```
```javascript
var db = TAFFY({record:1,text:"example"});
```
```javascript
var db = TAFFY([{"record":1,"text":"example"}]);
```
```javascript
var db = TAFFY('["{\"record\":1,\"text\":\"example\"}"]');
```
--------------------------------
### Create TaffyDB Database Instances
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Demonstrates how to create new TaffyDB database instances. Supports initialization with empty data, arrays of objects, JSON strings, or single objects. These instances can then be populated and queried.
```javascript
// Create an empty database
var db = TAFFY();
// Create database with initial data array
var products = TAFFY([
{ item: 1, name: "Blue Ray Player", price: 99.99 },
{ item: 2, name: "3D TV", price: 1799.99 },
{ item: 3, name: "Laptop", price: 899.99 }
]);
// Create database from JSON string
var users = TAFFY('[{"id":1,"name":"John"},{"id":2,"name":"Jane"}]');
// Create database with a single object
var config = TAFFY({ setting: "value", enabled: true });
```
--------------------------------
### DB Store Method
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Sets up a localStorage collection for the database. Changes are automatically synced. Can also be used to terminate storage.
```APIDOC
## POST /db/store
### Description
Sets up a localStorage collection for the database. Changes are automatically synced. Can also be used to terminate storage.
### Method
POST
### Endpoint
/db/store
### Parameters
#### Query Parameters
- **storageName** (string | boolean) - Required - The name for the localStorage collection. Pass `false` to terminate storing.
### Request Example
```json
{
"storageName": "myCollection"
}
```
### Response
#### Success Response (200)
- **result** (boolean) - `true` if data was returned from localStorage, `false` if no data returned or if localStorage is not available.
#### Response Example
```json
{
"result": true
}
```
```
--------------------------------
### Get Max Value of a Column in TaffyDB
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
The `max()` method returns the highest value for a specified column in a TaffyDB instance. It takes a single column name as an argument and returns a number or the value type of that column.
```javascript
db().max("balance");
// returns the highest value of the "balance" column.
```
--------------------------------
### Configure TaffyDB Settings
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
The `db.settings()` method allows modification of various TaffyDB configurations, including templates, case sensitivity, event handlers (`onInsert`, `onUpdate`, `onRemove`, `onDBChange`), cache size, and database name.
```javascript
db.settings({template:{show:true}}); // sets the template to have a show value set to true by default on all records
db.settings({onUpdate:function () {alert(this)}}); // sets the onUpdate event
```
--------------------------------
### Filter TaffyDB Records by Object Comparison (JavaScript)
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/index.html
These examples show how to filter records in a TaffyDB database using object comparison. You can filter by a single field or multiple fields to retrieve specific records that match the criteria.
```javascript
// Find all the friends in Seattle
friends({city:"Seattle, WA"});
```
```javascript
// Find John Smith, by ID
friends({id:1});
```
```javascript
// Find John Smith, by Name
friends({first:"John",last:"Smith"});
```
--------------------------------
### Create and Populate TaffyDB Database (JavaScript)
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/index.html
This snippet demonstrates how to create a new TaffyDB database and populate it with initial records. The TAFFY function takes an array of JavaScript objects, where each object represents a record in the database.
```javascript
var friends = TAFFY([
{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"},
{"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"},
{"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"},
{"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Active"}
]);
```
--------------------------------
### Access and Select Data from TaffyDB (JavaScript)
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/index.html
This snippet illustrates how to access individual records and specific data fields from a TaffyDB database. It also shows how to select an array of values for a particular field or get distinct values across records.
```javascript
// Kelly's record
var kelly = friends({id:2}).first();
```
```javascript
// Kelly's last name
var kellyslastname = kelly.last;
```
```javascript
// Get an array of record ids
var cities = friends().select("id");
```
```javascript
// Get an array of distinct cities
var cities = friends().distinct("city");
```
```javascript
// Apply a function to all the male friends
friends({gender:"M"}).each(function (r) {
alert(r.name + "!");
});
```
--------------------------------
### Supplant Data with Template in TaffyDB
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
The `supplant()` method merges records with a provided string template. Placeholders in the template, formatted as {key}, are replaced with actual values from the records. It can return a single string with all records merged or an array of strings if a second boolean argument is set to true.
```javascript
db().supplant("| {balance} |
");
// returns a string in this format "| -4 |
| 6 |
"
db().supplant("| {balance} |
",true);
// returns an array of strings format ["| -4 |
","| 6 |
"]
```
--------------------------------
### TaffyDB Querying
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Explains how to query the database using the database variable as a function, which returns a collection of methods for data manipulation.
```APIDOC
## DB Queries
### Description
Once you have a database, you can call the database variable as a function to set up a query and return a collection of methods to work with the results.
### Method
`db(query)`
### Parameters
#### Query Parameters
- **query** (String | Object | Array | Function) - Optional - The criteria for the query. Can be one or more Strings, Records, Filter Objects, Arrays, or Functions.
### Request Example
// Returns all rows in the database
```javascript
db();
```
// Example with a query object (assuming a 'name' field)
```javascript
db({name: "John Doe"});
```
### Response
#### Success Response (200)
- **Query Object** (Object) - A Query Object containing methods to further manipulate the results of the query.
#### Response Example
```json
{
"queryObject": "Methods for data manipulation"
}
```
```
--------------------------------
### Sort Records in TaffyDB (JavaScript)
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Explains how to sort query results in TaffyDB using the `order()` method. It supports various sorting directions including ascending, descending, logical, and logical descending. The examples show single and multi-column sorting with different data types.
```javascript
var files = TAFFY([
{ name: "file10.txt", size: 1024, modified: "2023-01-15" },
{ name: "file2.txt", size: 512, modified: "2023-03-20" },
{ name: "file1.txt", size: 2048, modified: "2023-02-10" }
]);
// Logical sort (default) - handles alphanumeric naturally
var logicalSort = files().order("name").select("name");
console.log(logicalSort); // Output: ["file1.txt", "file2.txt", "file10.txt"]
// Ascending alphabetical sort
var ascSort = files().order("name asec").select("name");
console.log(ascSort); // Output: ["file1.txt", "file10.txt", "file2.txt"]
// Descending sort
var descSort = files().order("size desc").select("size");
console.log(descSort); // Output: [2048, 1024, 512]
// Multi-column sort
var employees = TAFFY([
{ dept: "Sales", name: "John", salary: 50000 },
{ dept: "HR", name: "Alice", salary: 45000 },
{ dept: "Sales", name: "Bob", salary: 55000 }
]);
var sorted = employees().order("dept asec, salary desc").get();
// HR first, then Sales sorted by salary descending
```
--------------------------------
### Get Distinct Values from TaffyDB Columns
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
The `distinct()` method retrieves unique values from one or more specified columns. Similar to `select()`, it returns an array of values if a single column is provided, and an array of arrays if multiple columns are specified, with each inner array containing distinct values for the corresponding columns.
```javascript
db().distinct("title","gender");
// returns an array of arrays in this format [["Mr.","Male"],["Ms.","Female"]]
db().distinct("title");
// returns an array of values in this format ["Mr.","Ms.","Mrs."]
```
--------------------------------
### TaffyDB: Array for IN Clause
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/writing_queries.html
Demonstrates how to use an array to specify multiple values for a column, acting as an 'IN' clause in SQL. This allows for efficient querying when a column should match any value within a given set.
```javascript
db({"column":["value","value2"]});
// Real world example - records with a status of active or pending
db({"status":["Active","Pending"]});
```
--------------------------------
### Query TaffyDB Database
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Shows how to query a TaffyDB database. Calling the database variable as a function initiates a query and returns a Query Object with methods for data manipulation.
```javascript
db(); // returns all rows
```
--------------------------------
### TaffyDB: Comparison Operators - String Matching
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/writing_queries.html
Details TaffyDB operators for string matching. 'left' checks if a column starts with a given value. 'leftnocase' does the same but ignores case. 'right' checks if a column ends with a given value (case-sensitive). 'rightnocase' checks the end of a string ignoring case. 'like' checks if a column contains a given substring (case-sensitive). 'likenocase' checks for substring containment ignoring case. 'regex' matches a column against a regular expression.
```javascript
// left
// db({column:{left:value}})
// leftnocase
// db({column:{leftnocase:value}})
// right
// db({column:{right:value}})
// rightnocase
// db({column:{rightnocase:value}})
// like
// db({column:{like:value}})
// likenocase
// db({column:{likenocase:value}})
// regex
// db({column:{regex:value}});
```
--------------------------------
### Join TaffyDB Queries
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
The `join()` method is an experimental feature used to combine two TaffyDB instances or queries based on specified join conditions. Conditions can be provided as an array of column names for matching, an array with explicit comparison operators, or as a function that defines the join logic between the left (l) and right (r) records.
```javascript
// City DB
city_db = TAFFY([
{name:'New York',state:'NY'},
{name:'Las Vegas',state:'NV'},
{name:'Boston',state:'MA'}
]);
// State DB
state_db = TAFFY([
{name: 'New York', abbreviation: 'NY'},
{name: 'Nevada', abbreviation: 'NV'},
{name: 'Massachusetts', abbreviation: 'MA'}
]);
// Conditional Join
city_db()
.join( state_db, [ 'state', 'abbreviation' ]);
// Conditional Join with optional ===
city_db()
.join( state_db, [ 'state', '===', 'abbreviation' ]);
// Conditional Join using function
city_db()
.join( state_db, function (l, r) {
return (l.state === r.abbreviation);
});
```
--------------------------------
### Retrieve the First Record in TaffyDB
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Returns the first record from the set of records matching the TaffyDB query. If no records match, it returns undefined.
```javascript
db().first(); // returns the first record out of all matching records.
```
--------------------------------
### TaffyDB: Compound Equality Queries (AND)
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/writing_queries.html
Demonstrates how to combine multiple conditions in a TaffyDB query using a single Filter Object with comma-separated key-value pairs. This performs an AND operation, requiring all conditions to be met.
```javascript
// does a match for column that is a value and column2 is a value
db({column:"value",column2:"value"});
// Real world example - records with a status of active and a role of admin
db({status:"Active",role:"Admin"});
```
--------------------------------
### DB Settings Method
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Modifies settings for the database, such as template, event handlers, and cache size.
```APIDOC
## POST /db/settings
### Description
Modifies settings for the database, such as template, event handlers, and cache size.
### Method
POST
### Endpoint
/db/settings
### Parameters
#### Request Body
- **settings** (object) - Required - An object containing the settings to modify.
- **template** (object) - Optional - A template object merged with new records.
- **forcePropertyCase** (string) - Optional - Can be "lower" or "higher" to force property casing.
- **onInsert** (function) - Optional - Function to run on record insert.
- **onUpdate** (function) - Optional - Function to run on record update.
- **onRemove** (function) - Optional - Function to run on record remove.
- **onDBChange** (function) - Optional - Function to run on database change.
- **cacheSize** (number) - Optional - Size of cached query collection (0 to disable).
- **name** (string) - Optional - String name for the DB table.
### Request Example
```json
{
"settings": {
"template": {"show": true},
"onUpdate": "function() { alert(this) }"
}
}
```
### Response
#### Success Response (200)
- **settings** (object) - The current settings object for the database.
#### Response Example
```json
{
"settings": {
"template": {"show": true},
"forcePropertyCase": null,
"onInsert": null,
"onUpdate": "function() { alert(this) }",
"onRemove": null,
"onDBChange": null,
"cacheSize": 100,
"name": null
}
}
```
```
--------------------------------
### db().supplant()
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Merge records with a string template, replacing `{key}` placeholders with record values.
```APIDOC
## db().supplant()
### Description
Merge records with a string template, replacing `{key}` placeholders with record values.
### Method
`supplant(template, returnArray)`
### Endpoint
N/A (In-memory database operations)
### Parameters
#### Path Parameters
- **template** (string) - Required - The string template containing placeholders like `{key}`.
- **returnArray** (boolean) - Optional (defaults to `false`) - If `true`, returns an array of strings instead of a single concatenated string.
### Request Example
```javascript
var products = TAFFY([
{ name: "Laptop", price: 999.99, sku: "LP001" },
{ name: "Mouse", price: 29.99, sku: "MS002" }
]);
// Generate HTML table rows
var tableRows = products().supplant("| {name} | ${price} |
");
console.log(tableRows);
// Output: "| Laptop | $999.99 |
| Mouse | $29.99 |
"
// Return array of strings instead of concatenated string
var rowArray = products().supplant("{name} - {sku}", true);
console.log(rowArray);
// Output: ["Laptop - LP001", "Mouse - MS002"]
// Use for generating formatted output
var catalog = products().supplant("Product: {name} | SKU: {sku} | Price: ${price}\n");
console.log(catalog);
```
### Response
#### Success Response (200)
- **String** - A single string with placeholders replaced by record values (default behavior).
- **Array of strings** - An array where each element is a string with placeholders replaced by record values (when `returnArray` is `true`).
#### Response Example
```json
// For supplant("| {name} | ${price} |
")
"| Laptop | $999.99 |
| Mouse | $29.99 |
"
// For supplant("{name} - {sku}", true)
["Laptop - LP001", "Mouse - MS002"]
```
```
--------------------------------
### Configure TaffyDB Settings
Source: https://context7.com/typicaljoe/taffydb/llms.txt
The `db.settings()` method allows configuration of TaffyDB behavior, including default record templates, event handlers for data modifications, property case handling, query caching, and database naming. These settings affect how the database operates and interacts with data.
```javascript
var db = TAFFY();
db.settings({
template: { active: true, createdAt: new Date() },
forcePropertyCase: "lower",
onInsert: function() {
console.log("Inserted:", this.name);
},
onUpdate: function(oldRecord, changes) {
console.log("Updated from", oldRecord, "changes:", changes);
},
onRemove: function() {
console.log("Removed:", this.name);
},
onDBChange: function() {
console.log("Database changed, total records:", this.length);
},
cacheSize: 100,
name: "MyDatabase"
});
db.insert({ name: "Test Item" });
console.log(db().first().active);
```
--------------------------------
### TaffyDB db().get() Method
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Explains the `db().get()` method in TaffyDB, which returns an array of all matching records from a query. It's the recommended way to extract data from the database.
```javascript
var books = TAFFY([
{ title: "JavaScript Guide", author: "Smith", year: 2020 },
{ title: "Node.js Handbook", author: "Johnson", year: 2021 },
{ title: "React Patterns", author: "Smith", year: 2022 }
]);
// Get all records
var allBooks = books().get();
console.log(allBooks.length); // Output: 3
// Get filtered records
var smithBooks = books({ author: "Smith" }).get();
console.log(smithBooks);
// Output: [
// { title: "JavaScript Guide", author: "Smith", year: 2020, ___id: "...", ___s: true },
// { title: "React Patterns", author: "Smith", year: 2022, ___id: "...", ___s: true }
// ]
```
--------------------------------
### TaffyDB: Lookup and Update Record Using Record Object
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/writing_queries.html
Shows how to retrieve a record, store it in a variable, and then use that variable to look up and update the same record in TaffyDB. This is an alternative to using the record's ID directly.
```javascript
// get the first record
var firstRecord = db().first();
// look up this record again
db(firstRecord);
// Real world example - update records "status" column
db(firstRecord).update({status:"Active"});
```
--------------------------------
### String Templating with TaffyDB supplant()
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Merges records with a string template, replacing `{key}` placeholders with corresponding record values. Can output a single concatenated string or an array of strings.
```javascript
var products = TAFFY([
{ name: "Laptop", price: 999.99, sku: "LP001" },
{ name: "Mouse", price: 29.99, sku: "MS002" }
]);
// Generate HTML table rows
var tableRows = products().supplant("| {name} | ${price} |
");
console.log(tableRows);
// Output: "| Laptop | $999.99 |
| Mouse | $29.99 |
"
// Return array of strings instead of concatenated string
var rowArray = products().supplant("{name} - {sku}", true);
console.log(rowArray);
// Output: ["Laptop - LP001", "Mouse - MS002"]
// Use for generating formatted output
var catalog = products().supplant("Product: {name} | SKU: {sku} | Price: ${price}\n");
console.log(catalog);
```
--------------------------------
### TaffyDB: Compound Filter Objects (AND)
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/writing_queries.html
Illustrates how to chain multiple Filter Objects together when calling the TaffyDB root function. This also performs an AND operation, requiring records to match conditions in all provided Filter Objects.
```javascript
// does a match for column that is a value and column2 is a value
db({column:"value"},{column2:"value"});
// Real world example - records with a status of active and a role of admin
db({status:"Active"},{role:"Admin"});
```
--------------------------------
### Select Columns from TaffyDB
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
The `select()` method is used to retrieve specific columns from the database. It accepts one or more column names. If one column is specified, it returns an array of values for that column. If multiple columns are specified, it returns an array of arrays, where each inner array contains the values for the selected columns in the order they were provided.
```javascript
db().select("charges","credits","balance");
// returns an array of arrays in this format [[-24,20,-4]]
db().select("balance");
// returns an array of values in this format [-4,6,7,10]
```
--------------------------------
### db().get()
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Retrieves an array of all matching records from a TaffyDB collection. This is the recommended method for extracting data.
```APIDOC
## db().get()
### Description
Returns an array of all matching records. The preferred method for extracting data from the database.
### Method
`TAFFY(data).filter(query).get()`
### Parameters
None.
### Request Example
```javascript
var books = TAFFY([
{ title: "JavaScript Guide", author: "Smith", year: 2020 },
{ title: "Node.js Handbook", author: "Johnson", year: 2021 },
{ title: "React Patterns", author: "Smith", year: 2022 }
]);
// Get all records
var allBooks = books().get();
// Get filtered records
var smithBooks = books({ author: "Smith" }).get();
```
### Response
#### Success Response (200)
- **Array** - An array containing all records that match the query. Each record object may include internal TaffyDB properties like `___id` and `___s`.
```
--------------------------------
### Selective Data Retrieval with .get() and .stringify() in TaffyDB
Source: https://github.com/typicaljoe/taffydb/wiki/Suggestions-and-New-Feature-Ideas
The `.get()` and `.stringify()` methods in TaffyDB support retrieving 'trimmed' records by removing `___id` and `___s` values when `true` is passed. Alternatively, an array of column names can be provided to return objects containing only the specified fields, applicable to `.first()` and `.last()` as well.
```javascript
db.get(true);
db.stringify(true);
db.get(["first", "last", "zip"]);
db.first().get(["name", "age"]);
```
--------------------------------
### TaffyDB: Query Using a Function
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/writing_queries.html
Demonstrates how to use JavaScript functions within TaffyDB queries to apply custom filtering logic. The function should return 'true' for records that should be included in the results.
```javascript
// functional example, returns all records
db(function () {
return true;
});
// Real world example - function returns records with a status of active
db(function () {
return (this.status == "Active") ? true : false;
});
```
--------------------------------
### Insert Records into TaffyDB
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Shows how to insert single or multiple records into a TaffyDB instance. The `insert` method returns a query object pointing to the newly added records. An optional second argument can prevent triggering the `onInsert` event.
```javascript
var friends = TAFFY([
{ id: 1, name: "John", city: "Seattle" }
]);
// Insert a single record
friends.insert({ id: 2, name: "Kelly", city: "Dallas" });
// Insert multiple records
friends.insert([
{ id: 3, name: "Jeff", city: "Washington" },
{ id: 4, name: "Jennifer", city: "Seattle" }
]);
// Insert without triggering onInsert event
friends.insert({ id: 5, name: "Mike", city: "Boston" }, false);
// Verify insertion
console.log(friends().count()); // Output: 5
```
--------------------------------
### Store Data in TaffyDB using localStorage
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
The `db.store()` method enables persistence for TaffyDB collections using `localStorage`. If data exists, it's loaded; otherwise, it's saved automatically. Passing `false` terminates storage. This feature is browser-dependent.
```javascript
db.store("name"); // starts storing records in local storage
db.store(false); // terminates storing the collection
```
--------------------------------
### TaffyDB: Basic Equality Query
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/writing_queries.html
Explains the fundamental TaffyDB query syntax using a Filter Object to match records where a specific column equals a given value. This is the most common type of query.
```javascript
// does a match for column and value
db({column:"value"});
// Real world example - records with a status of active
db({status:"Active"});
// This is the short form of this
// does a match for column and value
db({column:{is:"value"}});
// Real world example - records with a status of active
db({status:{is:"Active"}});
```
--------------------------------
### DB Insert Method
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Inserts records into the database. You can optionally control whether the onInsert event is triggered.
```APIDOC
## POST /db/insert
### Description
Inserts records into the database. You can optionally control whether the onInsert event is triggered.
### Method
POST
### Endpoint
/db/insert
### Parameters
#### Query Parameters
- **records** (object | array | string) - Required - An object, array of objects, or JSON strings to insert.
- **runOnInsertEvent** (boolean) - Optional - `true` to run the onInsert event (default), `false` to skip.
### Request Example
```json
{
"records": {"column": "value"},
"runOnInsertEvent": false
}
```
### Response
#### Success Response (200)
- **query** (object) - A query object pointing to the inserted records.
#### Response Example
```json
{
"query": "[query object]"
}
```
```
--------------------------------
### db().sum(), db().min(), db().max()
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Aggregate functions for numeric calculations on column values.
```APIDOC
## db().sum(), db().min(), db().max()
### Description
Aggregate functions for numeric calculations on column values.
### Method
`sum(column1, column2, ...)`
`min(column)`
`max(column)`
### Endpoint
N/A (In-memory database operations)
### Parameters
#### Query Parameters
- **column** (string) - Required - The name of the numeric column to perform the aggregation on.
- **column1, column2, ...** (string) - Required for `sum` - The names of the numeric columns to sum.
### Request Example
```javascript
var sales = TAFFY([
{ product: "Widget", quantity: 100, revenue: 1000 },
{ product: "Gadget", quantity: 50, revenue: 2500 },
{ product: "Gizmo", quantity: 75, revenue: 1500 }
]);
// Sum of column values
var totalRevenue = sales().sum("revenue");
console.log(totalRevenue); // Output: 5000
// Sum multiple columns
var totalAll = sales().sum("quantity", "revenue");
console.log(totalAll); // Output: 5225 (225 + 5000)
// Minimum value
var minRevenue = sales().min("revenue");
console.log(minRevenue); // Output: 1000
// Maximum value
var maxQuantity = sales().max("quantity");
console.log(maxQuantity); // Output: 100
// Aggregates on filtered data
var highRevenueSum = sales({ revenue: { gt: 1000 } }).sum("revenue");
console.log(highRevenueSum); // Output: 4000
```
### Response
#### Success Response (200)
- **Aggregated value** (number) - The result of the sum, min, or max operation.
#### Response Example
```json
// For sum("revenue")
5000
// For min("revenue")
1000
// For max("quantity")
100
```
```
--------------------------------
### Iterate and Transform Records with TaffyDB each() and map()
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Provides methods for iterating over records. `each()` is used for performing side effects on each record, while `map()` transforms records into a new array based on a provided function.
```javascript
var users = TAFFY([
{ name: "John", email: "john@example.com", active: true },
{ name: "Kelly", email: "kelly@example.com", active: false },
{ name: "Jeff", email: "jeff@example.com", active: true }
]);
// each - iterate with side effects
users({ active: true }).each(function(record, index) {
console.log(`${index}: ${record.name} - ${record.email}`);
});
// Output:
// 0: John - john@example.com
// 1: Jeff - jeff@example.com
// map - transform records into new array
var emailList = users().map(function(record) {
return `${record.name} <${record.email}>`;
});
console.log(emailList);
// Output: ["John ", "Kelly ", "Jeff "]
// map with calculations
var balances = TAFFY([
{ account: "A1", balance: 1000 },
{ account: "A2", balance: 2500 }
]);
var withInterest = balances().map(function(r) {
return { account: r.account, projected: r.balance * 1.05 };
});
console.log(withInterest);
// Output: [{ account: "A1", projected: 1050 }, { account: "A2", projected: 2625 }]
```
--------------------------------
### Basic TaffyDB Queries with Filter Objects
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Explains how to query TaffyDB using filter objects. This method allows for precise data retrieval based on exact matches, multiple conditions (AND logic), or comparisons using operators like 'gt' (greater than).
```javascript
var employees = TAFFY([
{ id: 1, name: "John", department: "Sales", salary: 50000 },
{ id: 2, name: "Kelly", department: "HR", salary: 45000 },
{ id: 3, name: "Jeff", department: "Sales", salary: 55000 },
{ id: 4, name: "Jennifer", department: "IT", salary: 60000 }
]);
// Query all records
employees();
// Find by exact match
employees({ department: "Sales" });
// Multiple conditions (AND)
employees({ department: "Sales", salary: 50000 });
// Equivalent using multiple filter objects
employees({ department: "Sales" }, { salary: { gt: 45000 } });
// Using internal record ID
var firstRecord = employees().first();
employees(firstRecord); // Look up by record reference
employees(firstRecord.___id); // Look up by ID string
```
--------------------------------
### TaffyDB db().first() and db().last() Methods
Source: https://context7.com/typicaljoe/taffydb/llms.txt
Details the `db().first()` and `db().last()` methods in TaffyDB for retrieving the first or last record from a query result set. These methods return `false` if no records match.
```javascript
var scores = TAFFY([
{ player: "Alice", score: 150 },
{ player: "Bob", score: 200 },
{ player: "Charlie", score: 175 }
]);
// Get first record
var first = scores().first();
console.log(first.player); // Output: "Alice"
// Get last record
var last = scores().last();
console.log(last.player); // Output: "Charlie"
// First/last from filtered results
var highScorer = scores({ score: { gt: 160 } }).first();
console.log(highScorer.player); // Output: "Bob"
// Returns false if no records match
var noMatch = scores({ score: { gt: 500 } }).first();
console.log(noMatch); // Output: false
```
--------------------------------
### DB Order Method
Source: https://github.com/typicaljoe/taffydb/blob/master/docs/working_with_data.html
Sorts the database records by specified columns. Logical sorting is the default behavior.
```APIDOC
## POST /db/order
### Description
Sorts the database records by specified columns. Logical sorting is the default behavior.
### Method
POST
### Endpoint
/db/order
### Parameters
#### Query Parameters
- **columns** (string) - Required - A comma-separated string of columns to order by.
- **direction** (string) - Optional - Can be 'asec', 'desc', 'logical', or 'logicaldesc' to influence sort direction.
### Request Example
```json
{
"columns": "column1,column2",
"direction": "desc"
}
```
### Response
#### Success Response (200)
- **result** (boolean) - `true` indicating the sort operation was successful.
#### Response Example
```json
{
"result": true
}
```
```