json-fetchfy
Version:
A lightweight Node.js module to fetch, validate, and manipulate JSON data from various sources seamlessly.
244 lines (225 loc) • 6.33 kB
JavaScript
/**
* Json Generator - A utility module for data processing and caching
* @module jsonGenerator
*/
// =================
// Main Module Object
// =================
const jsonGenerator = {};
/**
* Test Data Generator Configuration
* Defines available field types and their generators
* @private
*/
const _dataGenerators = {
id: (index) => index + 1,
uuid: () => crypto.randomUUID(),
name: () => {
const names = [
"John",
"Jane",
"Alex",
"Maria",
"James",
"Emma",
"Michael",
"Sarah",
"David",
"Lisa",
"Robert",
"Anna",
"William",
"Sofia",
"Richard",
"Emily",
];
const surnames = [
"Smith",
"Johnson",
"Williams",
"Brown",
"Jones",
"Garcia",
"Miller",
"Davis",
"Rodriguez",
"Martinez",
"Hernandez",
"Lopez",
"Gonzalez",
];
return `${names[Math.floor(Math.random() * names.length)]} ${
surnames[Math.floor(Math.random() * surnames.length)]
}`;
},
age: () => Math.floor(Math.random() * (80 - 18 + 1)) + 18,
email: (name) => {
const domains = [
"gmail.com",
"yahoo.com",
"hotmail.com",
"outlook.com",
"example.com",
];
const normalizedName = name.toLowerCase().replace(/\s+/g, ".");
return `${normalizedName}@${
domains[Math.floor(Math.random() * domains.length)]
}`;
},
date: () => {
const start = new Date(2020, 0, 1);
const end = new Date();
return new Date(
start.getTime() + Math.random() * (end.getTime() - start.getTime())
)
.toISOString()
.split("T")[0];
},
description: () => {
const adjectives = [
"Amazing",
"Brilliant",
"Creative",
"Dynamic",
"Efficient",
];
const nouns = [
"professional",
"individual",
"contributor",
"team player",
"expert",
];
const verbs = [
"specializes in",
"focuses on",
"excels at",
"works with",
"develops",
];
const fields = [
"technology",
"business",
"design",
"development",
"innovation",
];
return `${adjectives[Math.floor(Math.random() * adjectives.length)]} ${
nouns[Math.floor(Math.random() * nouns.length)]
} who ${verbs[Math.floor(Math.random() * verbs.length)]} ${
fields[Math.floor(Math.random() * fields.length)]
}.`;
},
boolean: () => Math.random() > 0.5,
number: (min = 0, max = 1000) =>
Math.floor(Math.random() * (max - min + 1)) + min,
phone: () => {
const areaCode = Math.floor(Math.random() * 900) + 100;
const prefix = Math.floor(Math.random() * 900) + 100;
const lineNum = Math.floor(Math.random() * 9000) + 1000;
return `${areaCode}-${prefix}-${lineNum}`;
},
};
/**
* Generates test JSON data based on specified fields and options.
*
* @param {Object} options - Configuration options for data generation
* @param {Array<string|Object>} options.fields - Fields to include in generated data
* @param {number} [options.count=1] - Number of records to generate
* @param {boolean} [options.returnArray=true] - Whether to return an array even for single records
* @param {Object} [options.fieldOptions] - Custom options for specific fields
*
* @returns {Object|Array} Generated test data
*
* @example
* // Generate 3 records with basic fields
* jsonGenerator.generateTestData({
* fields: ['id', 'name', 'age'],
* count: 3
* });
*
* @example
* // Generate data with custom field options
* jsonGenerator.generateTestData({
* fields: [
* 'id',
* { name: 'score', type: 'number', min: 0, max: 100 },
* { name: 'customField', generator: () => 'custom value' }
* ],
* count: 2
* });
*
* @throws {Error} If invalid fields or options are provided
*/
jsonGenerator.generateTestData = (options = {}) => {
// Default options
const {
fields = ["id", "name"],
count = 1,
returnArray = true,
fieldOptions = {},
} = options;
// Validate inputs
if (!Array.isArray(fields) || fields.length === 0) {
throw new Error("Fields must be a non-empty array");
}
if (count < 1) {
throw new Error("Count must be a positive number");
}
// Generate records
const generateRecord = (index) => {
const record = {};
let recordName; // Store name if generated, for email generation
fields.forEach((field) => {
// Handle both string fields and object fields with custom options
const fieldName = typeof field === "string" ? field : field.name;
const fieldType =
typeof field === "string" ? field : field.type || fieldName;
const generator = typeof field === "object" && field.generator;
// Use custom generator if provided
if (generator && typeof generator === "function") {
record[fieldName] = generator(index);
return;
}
// Handle special case for email (needs name)
if (fieldType === "email" && recordName) {
record[fieldName] = _dataGenerators.email(recordName);
return;
}
// Use built-in generator with custom options if available
const baseGenerator = _dataGenerators[fieldType];
if (!baseGenerator) {
throw new Error(`Unknown field type: ${fieldType}`);
}
// Generate value using field options if available
const fieldOpts = fieldOptions[fieldName] || {};
record[fieldName] = baseGenerator(index, fieldOpts);
// Store name for email generation if needed
if (fieldType === "name") {
recordName = record[fieldName];
}
});
return record;
};
// Generate all records
const records = Array.from({ length: count }, (_, index) =>
generateRecord(index)
);
// Return based on count and returnArray option
return count === 1 && !returnArray ? records[0] : records;
};
// /**
// * Validates test data generation options
// * @private
// */
// jsonGenerator._validateTestDataOptions = (options) => {
// const {
// fields,
// count,
// returnArray,
// fieldOptions
// } = options;
// // Add validation logic here if needed
// // This is a placeholder for future validation requirements
// };
export default jsonGenerator;