json-fetchfy
Version:
A lightweight Node.js module to fetch, validate, and manipulate JSON data from various sources seamlessly.
282 lines (215 loc) • 7.8 kB
Markdown
Certainly! Here's a detailed usage guide for the `fetchfy` module, including both basic and advanced examples.
## `fetchfy` - Data Processing and Caching Utility
`fetchfy` is a utility module designed to handle JSON data manipulation, searching, and caching. This module is flexible for handling arrays, objects, and custom data structures, offering robust options for validation, updating, searching, and more.
### Table of Contents
- [Installation](#installation)
- [Basic Usage](#basic-usage)
- [Advanced Usage](#advanced-usage)
- [API Reference](#api-reference)
### Installation
```bash
npm install json-fetchfy
```
To use `fetchfy`, import the module and its dependencies into your project.
```js
import fetchfy from "json-fetchfy";
```
### Basic Usage
#### 1. Detecting JSON Content Type
You can determine the type of content in a JSON file or string (such as numbers, strings, objects, or single entries).
```js
const jsonContent = '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]';
const type = fetchfy.detectJsonContentType(jsonContent);
console.log(type); // Output: "Objects"
```
#### 2. Setting and Retrieving Options
Manage the module's options to control behavior like cache usage, case sensitivity, and limit on results.
```js
// Setting options
fetchfy.options({ cache: true, caseSensitive: false, limit: 10 });
// Retrieving current options
const currentOptions = fetchfy.options("get");
console.log(currentOptions);
```
#### 3. Retrieving Data with a Query
Retrieve items from JSON data based on a query. Useful for finding specific entries in a JSON array.
```js
const data = [
{ id: 1, name: "Alice", age: 30 },
{ id: 2, name: "Bob", age: 25 },
];
const results = fetchfy.get(data, "Alice", "name");
console.log(results); // Output: [{ id: 1, name: "Alice", age: 30 }]
```
### Advanced Usage
#### 1. Updating JSON Data with a Query
Update fields in JSON data based on a search query, with optional save to a file.
```js
const data = [
{ id: 1, name: "Alice", age: 30 },
{ id: 2, name: "Bob", age: 25 },
];
const updatedData = fetchfy.update(data, "Alice", "name", {
update: { age: 31 },
save: true,
});
console.log(updatedData);
// Output: [
// { id: 1, name: "Alice", age: 31 },
// { id: 2, name: "Bob", age: 25 }
// ]
```
#### 2. Adding New Items with Unique Validation
Add items to JSON data with optional validation and unique constraints. You can ensure that fields are unique and IDs are auto-incremented.
```js
const users = [
{ id: 1, name: "Alice", age: 30 },
{ id: 2, name: "Bob", age: 25 },
];
const newUser = { name: "Charlie", age: 28 };
const result = fetchfy.add(users, newUser, {
unique: true,
uniqueKeys: ["name"],
id: "auto",
});
console.log(result);
// Output: { success: true, data: [{ id: 1, name: "Alice" ...}, { id: 2, ...}, { id: 3, name: "Charlie", age: 28 }]}
```
#### 3. Reordering Object Properties Alphabetically
Reorder the properties of an object alphabetically or with a specified ID field first.
```js
const user = { age: 30, name: "Alice", id: 1 };
const orderedUser = fetchfy._orderProperties(user, { alphabetical: true, idKey: "id" });
console.log(orderedUser);
// Output: { id: 1, age: 30, name: "Alice" }
```
#### 4. Complex Search with Case Sensitivity and Deep Search
Perform complex searches with options for case sensitivity, deep search, and result limits.
```js
const data = [
{ id: 1, name: "Alice", details: { age: 30 } },
{ id: 2, name: "bob", details: { age: 25 } },
];
const options = {
caseSensitive: false,
deep: true,
limit: 5,
};
const results = fetchfy.get(data, "alice", "name", options);
console.log(results);
// Output: [{ id: 1, name: "Alice", details: { age: 30 } }]
```
#### 5. Auto-Incrementing IDs with Data Validation
Add new items with auto-incrementing IDs while validating structure and ensuring no duplicates are added.
```js
const data = [
{ id: 1, name: "Alice", age: 30 },
{ id: 2, name: "Bob", age: 25 },
];
const newUser = { name: "Alice", age: 31 };
const result = fetchfy.add(data, newUser, {
unique: true,
uniqueKeys: ["name"],
id: "auto",
validate: true,
});
console.log(result);
// Output: { success: false, message: "Duplicate entry found" }
```
### Enhanced Usage with File Paths
In this setup, `fetchfy.get`, `fetchfy.update`, and `fetchfy.add` support file paths, so JSON data operations interact directly with the file system. These methods:
- Read from the file at the start.
- Apply any specified operations.
- Save changes back to the file if required (like with updates and additions).
#### Sample `data.json` File
```json
[
{ "id": 1, "name": "Alice", "age": 30 },
{ "id": 2, "name": "Bob", "age": 25 }
]
```
### Example Code with File Paths
Here’s how you might use the enhanced `fetchfy` methods with JSON files directly.
#### 1. Retrieving Data from a JSON File
Retrieve an entry by specifying the file path.
```js
const user = fetchfy.get('./data.json', "Alice", "name");
console.log("User found:", user);
// Output: [{ "id": 1, "name": "Alice", "age": 30 }]
```
#### 2. Updating an Entry in a JSON File
Update data for a user in `data.json` and save changes.
```js
const updateResult = fetchfy.update('./data.json', "Alice", "name", {
update: { age: 31 },
save: true // default is false
});
if (updateResult.success) {
console.log("User updated and saved to file:", updateResult.data);
} else {
console.log("Update failed:", updateResult.message);
}
// Expected content of data.json after update:
// [
// { "id": 1, "name": "Alice", "age": 31 },
// { "id": 2, "name": "Bob", "age": 25 }
// ]
```
#### 3. Adding a New Entry with Unique Validation
Add a new user to `data.json`, ensuring uniqueness by name, and save the updated array to the file.
```js
const addResult = fetchfy.add('./data.json', { name: "Charlie", age: 28 }, {
unique: true,
uniqueKeys: ["name"],
id: "auto",
save: true // default is false
});
if (addResult.success) {
console.log("New user added and saved:", addResult.data);
} else {
console.log("User could not be added:", addResult.message);
}
// Expected content of data.json after addition:
// [
// { "id": 1, "name": "Alice", "age": 31 },
// { "id": 2, "name": "Bob", "age": 25 },
// { "id": 3, "name": "Charlie", "age": 28 }
// ]
```
### API Reference
#### `fetchfy.detectJsonContentType(jsonInput)`
- **Description**: Detects the content type of JSON input.
- **Parameters**:
- `jsonInput` (string|object): JSON data to analyze.
- **Returns**: Content type as string (e.g., "Numbers", "Strings", "Objects").
#### `fetchfy.options(options)`
- **Description**: Sets or retrieves module options.
- **Parameters**:
- `options` (object|string): Options object or `"get"` to retrieve current options.
#### `fetchfy.get(data, query, key, options)`
- **Description**: Retrieves data based on a query.
- **Parameters**:
- `data` (Array|Object): Data to search in.
- `query` (any): Search query.
- `key` (string|null): Key for object search.
- `options` (object): Additional search options.
#### `fetchfy.update(data, query, key, options)`
- **Description**: Updates JSON data matching a query.
- **Parameters**:
- `data` (Array|Object): Data to update.
- `query` (any): Search query for the items to update.
- `key` (string|null): Key for object search.
- `options` (object): Update options (e.g., `save`, `update` fields).
#### `fetchfy.add(data, items, options)`
- **Description**: Adds new items to JSON data with optional validation.
- **Parameters**:
- `data` (Array|Object): Data structure to add items to.
- `items` (any|Array): Single or array of items to add.
- `options` (object): Additional options (`validate`, `unique`, `id` for auto-incrementing).