### Install mockaroo Node.js Package Source: https://github.com/mockaroo/mockaroo-node/blob/master/README.md Install the mockaroo npm package using npm. This is the primary step to integrate Mockaroo data generation into your Node.js project. ```bash npm install mockaroo ``` -------------------------------- ### Generate Complex Mockaroo Data with Various Field Types in Node.js Source: https://context7.com/mockaroo/mockaroo-node/llms.txt An example demonstrating how to generate a dataset with 50 records using various complex field types available in Mockaroo, such as UUID, custom lists, money, dates, datetimes, and IP addresses. Requires the 'mockaroo' package. ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateComplexData() { const data = await client.generate({ count: 50, fields: [ { name: 'user_id', type: 'UUID' }, { name: 'first_name', type: 'First Name' }, { name: 'last_name', type: 'Last Name' }, { name: 'email', type: 'Email Address' }, { name: 'age', type: 'Number', min: 18, max: 80, decimals: 0 }, { name: 'account_status', type: 'Custom List', values: ['active', 'pending', 'suspended', 'closed'] }, { name: 'balance', type: 'Money', min: 0, max: 100000, decimals: 2, symbol: '$' }, { name: 'signup_date', type: 'Date', min: '1/1/2020', max: '12/31/2024', format: '%Y-%m-%d' }, { name: 'last_login', type: 'Datetime', min: '1/1/2024 00:00:00', max: '12/31/2024 23:59:59', format: '%Y-%m-%dT%H:%M:%S' }, { name: 'ip_address', type: 'IP Address v4' }, { name: 'phone', type: 'Phone' }, { name: 'city', type: 'City' }, { name: 'state', type: 'State (abbrev)' }, { name: 'zip', type: 'Zip Code' } ] }); console.log(`Generated ${data.length} complex records`); data.slice(0, 3).forEach((record) => { console.log(JSON.stringify(record, null, 2)); }); return data; } generateComplexData(); ``` -------------------------------- ### Client Constructor Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Initializes a new Mockaroo client instance. This client is used to interact with the Mockaroo API for generating mock data. Configuration options include API key, host, port, and security settings. ```APIDOC ## Client Constructor ### Description Initializes a new Mockaroo client instance with authentication and connection configuration. ### Method `new Mockaroo.Client(options)` ### Parameters #### Request Body - **apiKey** (string) - Required - Your Mockaroo API key. - **host** (string) - Optional - The API host. Defaults to 'api.mockaroo.com'. - **port** (number | null) - Optional - Custom port if needed. Defaults to null. - **secure** (boolean) - Optional - Use HTTPS (default: true) or HTTP. ### Request Example ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key-here', host: 'api.mockaroo.com', port: null, secure: true }); ``` ``` -------------------------------- ### Initialize Mockaroo Client (Node.js) Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Creates a new Mockaroo client instance. Requires an API key and allows configuration of host, port, and security (HTTPS/HTTP). ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key-here', // Required: Get from https://mockaroo.com/api/docs host: 'api.mockaroo.com', // Optional: Default is api.mockaroo.com port: null, // Optional: Custom port if needed secure: true // Optional: Use HTTPS (default) or HTTP }); // Example with custom configuration const devClient = new Mockaroo.Client({ apiKey: 'dev-key', host: 'localhost', port: 3000, secure: false }); ``` -------------------------------- ### Run Tests for mockaroo-node Source: https://github.com/mockaroo/mockaroo-node/blob/master/README.md Execute the test suite for the mockaroo-node module using yarn. This command runs the tests defined within the project, typically using mocha and chai. ```bash yarn test ``` -------------------------------- ### Generate with Dynamic Fields Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Defines the data structure inline using field definitions, including their names, types, and specific parameters. This provides flexibility for generating custom datasets on the fly. ```APIDOC ## Generate with Dynamic Fields ### Description Define data structure inline using field definitions with types and parameters. ### Method `client.generate(options)` ### Endpoint `/api/generator/` ### Parameters #### Request Body - **count** (number) - Required - The number of records to generate. - **fields** (Array) - Required - An array of field definitions. - **name** (string) - Required - The name of the field. - **type** (string) - Required - The data type of the field (e.g., 'Row Number', 'Custom List', 'Number', 'Date'). - **values** (Array) - Optional - Used with 'Custom List' type. - **min** (number | string) - Optional - Minimum value for 'Number' or date string for 'Date'. - **max** (number | string) - Optional - Maximum value for 'Number' or date string for 'Date'. - **decimals** (number) - Optional - Number of decimal places for 'Number' type. - **format** (string) - Optional - Date format string for 'Date' type. ### Request Example ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateTransactionData() { try { const transactions = await client.generate({ count: 100, fields: [ { name: 'id', type: 'Row Number' }, { name: 'transactionType', type: 'Custom List', values: ['credit', 'debit'] }, { name: 'amount', type: 'Number', min: 1, max: 10000, decimals: 2 }, { name: 'merchant', type: 'Company Name' }, { name: 'date', type: 'Date', min: '1/1/2024', max: '12/31/2024', format: '%Y-%m-%d' } ] }); console.log(transactions); return transactions; } catch (error) { console.error('Error:', error.message); } } generateTransactionData(); ``` ### Response #### Success Response (200) - **Array of objects** - Each object represents a generated record with dynamically defined fields. #### Response Example ```json [ { "id": 1, "transactionType": "credit", "amount": 123.45, "merchant": "Example Corp", "date": "2024-05-15" } ] ``` ``` -------------------------------- ### Generate CSV Format Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Generates mock data and returns it in CSV format. Options include specifying the number of records, whether to include a header row, and defining the fields. ```APIDOC ## Generate CSV Format ### Description Generate mock data in CSV format with optional header configuration. ### Method `client.generate(options)` ### Endpoint `/api/generator/` ### Parameters #### Request Body - **count** (number) - Required - The number of records to generate. - **format** (string) - Required - Set to 'csv' for CSV output. - **header** (boolean) - Optional - Include header row (default: true). - **fields** (Array) - Required - An array of field definitions (same as dynamic fields). - **name** (string) - Required - The name of the field. - **type** (string) - Required - The data type of the field. ### Request Example ```javascript const Mockaroo = require('mockaroo'); const fs = require('fs'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateCSV() { try { const csvData = await client.generate({ count: 1000, format: 'csv', header: true, fields: [ { name: 'first_name', type: 'First Name' }, { name: 'last_name', type: 'Last Name' }, { name: 'email', type: 'Email Address' }, { name: 'country', type: 'Country' } ] }); fs.writeFileSync('users.csv', csvData); console.log('CSV file created successfully'); return csvData; } catch (error) { console.error('CSV generation failed:', error.message); } } generateCSV(); ``` ### Response #### Success Response (200) - **string** - The generated data in CSV format. #### Response Example ```csv first_name,last_name,email,country John,Doe,john.doe@example.com,USA Jane,Smith,jane.smith@example.com,Canada ``` ``` -------------------------------- ### Generate Data with Dynamic Fields (Node.js) Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Defines the data structure inline using field definitions, including name, type, and parameters. This method allows for on-the-fly data structure creation for specific use cases like transaction data. ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateTransactionData() { try { const transactions = await client.generate({ count: 100, fields: [ { name: 'id', type: 'Row Number' }, { name: 'transactionType', type: 'Custom List', values: ['credit', 'debit'] }, { name: 'amount', type: 'Number', min: 1, max: 10000, decimals: 2 }, { name: 'merchant', type: 'Company Name' }, { name: 'date', type: 'Date', min: '1/1/2024', max: '12/31/2024', format: '%Y-%m-%d' } ] }); transactions.forEach((tx) => { console.log(`[${tx.id}] ${tx.transactionType} of $${tx.amount} at ${tx.merchant} on ${tx.date}`); }); return transactions; } catch (error) { if (error instanceof Mockaroo.errors.UsageLimitExceededError) { console.error('Daily usage limit exceeded'); } else { console.error('Error:', error.message); } } } generateTransactionData(); ``` -------------------------------- ### Generate Data from Saved Schema Source: https://github.com/mockaroo/mockaroo-node/blob/master/README.md Generate data by referencing a pre-defined schema saved on Mockaroo. Requires an API key and the schema name. The 'generate' method returns a promise that resolves to an array of records. ```javascript const Mockaroo = require("mockaroo"); const client = new Mockaroo.Client({ apiKey: "(your api key)\ ``` -------------------------------- ### Generate Data with Dynamic Fields Source: https://github.com/mockaroo/mockaroo-node/blob/master/README.md Generate data by dynamically specifying fields and their types directly in the API request. This method allows for on-the-fly data structure definition without needing a pre-saved schema. ```javascript const records = await client.generate({ count: 10, fields: [ { name: "id", type: "Row Number", }, { name: "transactionType", type: "Custom List", values: ["credit", "debit"], }, ], }); ``` -------------------------------- ### Generate Single Mockaroo Record as Object or Array in Node.js Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Shows how to generate a single data record from Mockaroo. By default, count: 1 returns an object, but the 'array: true' option ensures an array format even for a single record. Requires the 'mockaroo' package. ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateSingleUser() { // When count is 1, returns a single object (not an array) const user = await client.generate({ count: 1, fields: [ { name: 'id', type: 'UUID' }, { name: 'username', type: 'Username' }, { name: 'email', type: 'Email Address' }, { name: 'created_at', type: 'Datetime' } ] }); console.log('New user:', user); // Output: { id: '...', username: '...', email: '...', created_at: '...' } return user; } // Force array format even for single record async function generateSingleUserAsArray() { const users = await client.generate({ count: 1, array: true, // Returns array even when count is 1 fields: [ { name: 'username', type: 'Username' } ] }); console.log('Users array:', users); // Output: [{ username: '...' }] return users; } generateSingleUser(); ``` -------------------------------- ### Handle Mockaroo API Errors with Custom Classes in Node.js Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Demonstrates how to handle specific Mockaroo API errors, including invalid API keys, usage limits, and general API errors, using custom error classes. It includes a retry mechanism for transient errors. Requires the 'mockaroo' package. ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateWithErrorHandling() { try { const records = await client.generate({ count: 10, schema: 'My Schema' }); console.log('Success:', records); return records; } catch (error) { if (error instanceof Mockaroo.errors.InvalidApiKeyError) { console.error('Authentication failed: Invalid API key'); console.error('Get your API key at: https://mockaroo.com/api/docs'); } else if (error instanceof Mockaroo.errors.UsageLimitExceededError) { console.error('Usage limit exceeded for your plan'); console.error('See limits at: https://mockaroo.com/api/docs'); } else if (error instanceof Mockaroo.errors.ApiError) { console.error('API error:', error.message); } else { console.error('Unexpected error:', error); } throw error; } } // Example with retry logic async function generateWithRetry(maxRetries = 3) { let attempt = 0; while (attempt < maxRetries) { try { return await client.generate({ count: 10, fields: [ { name: 'id', type: 'Row Number' }, { name: 'name', type: 'Full Name' } ] }); } catch (error) { attempt++; if (error instanceof Mockaroo.errors.InvalidApiKeyError) { throw error; // Don't retry authentication errors } if (attempt >= maxRetries) { throw error; } console.log(`Attempt ${attempt} failed, retrying...`); await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); } } } generateWithErrorHandling(); ``` -------------------------------- ### Generate Data from Saved Schema (Node.js) Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Generates mock data using a schema previously saved on Mockaroo.com. It specifies the number of records and the schema name. Handles potential errors during generation. ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateFromSchema() { try { const records = await client.generate({ count: 10, schema: 'My Saved Schema' }); console.log(`Generated ${records.length} records`); records.forEach((record, i) => { console.log(`Record ${i}:`, record); }); return records; } catch (error) { console.error('Generation failed:', error.message); throw error; } } generateFromSchema(); ``` -------------------------------- ### Generate Data in CSV Format (Node.js) Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Generates mock data and formats it as CSV. Supports configuration for including a header row and defining fields. The generated CSV data can be saved to a file. ```javascript const Mockaroo = require('mockaroo'); const fs = require('fs'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateCSV() { try { const csvData = await client.generate({ count: 1000, format: 'csv', header: true, // Include header row (default: true) fields: [ { name: 'first_name', type: 'First Name' }, { name: 'last_name', type: 'Last Name' }, { name: 'email', type: 'Email Address' }, { name: 'country', type: 'Country' } ] }); // Save to file fs.writeFileSync('users.csv', csvData); console.log('CSV file created successfully'); return csvData; } catch (error) { console.error('CSV generation failed:', error.message); } } // Generate CSV without header async function generateCSVNoHeader() { const csvData = await client.generate({ count: 100, format: 'csv', header: false, // Exclude header row fields: [ { name: 'id', type: 'Row Number' }, { name: 'value', type: 'Number', min: 1, max: 100 } ] }); return csvData; } generateCSV(); ``` -------------------------------- ### Generate Data in CSV Format Source: https://github.com/mockaroo/mockaroo-node/blob/master/README.md Generate data and download it directly in CSV format. The 'format' option is set to 'csv', and the 'header' option controls whether the CSV includes a header row (defaults to true). ```javascript const records = await client.generate({ count: 10, format: 'csv', header: true, // this is the default, set to false to remove the header row fields: [...] // field definitions as shown previously }) ``` -------------------------------- ### Process Generated Records Source: https://github.com/mockaroo/mockaroo-node/blob/master/README.md Iterate through the array of generated records returned by the client.generate method. Each record object's keys correspond to the field names defined in the schema or fields parameter. ```javascript const records = await client.generate({ count: 10, fields: [ { name: "id", type: "Row Number", }, { name: "transactionType", type: "Custom List", values: ["credit", "debit"], }, ], }); records.forEach((record, i) => { console.log( `[${i}] id: ${record.id}, transactionType: ${record.transactionType}` ); }); ``` -------------------------------- ### Generate from Saved Schema Source: https://context7.com/mockaroo/mockaroo-node/llms.txt Generates mock data using a schema that has been previously saved on the Mockaroo website. This is useful for reusing existing data structures. ```APIDOC ## Generate from Saved Schema ### Description Generate mock data using a schema saved on Mockaroo.com website. ### Method `client.generate(options)` ### Endpoint `/api/generator/saved/` ### Parameters #### Request Body - **count** (number) - Required - The number of records to generate. - **schema** (string) - Required - The name of the saved schema. ### Request Example ```javascript const Mockaroo = require('mockaroo'); const client = new Mockaroo.Client({ apiKey: 'your-api-key' }); async function generateFromSchema() { try { const records = await client.generate({ count: 10, schema: 'My Saved Schema' }); console.log(`Generated ${records.length} records`); return records; } catch (error) { console.error('Generation failed:', error.message); throw error; } } generateFromSchema(); ``` ### Response #### Success Response (200) - **Array of objects** - Each object represents a generated record according to the schema. #### Response Example ```json [ { "field1": "value1", "field2": "value2" } ] ``` ``` -------------------------------- ### Handle Mockaroo API Errors Source: https://github.com/mockaroo/mockaroo-node/blob/master/README.md Implement error handling for API requests using try-catch blocks. The module provides specific error classes like InvalidApiKeyError, UsageLimitExceededError, and ApiError for granular error management. ```javascript try { const records = await client.generate({ count: 10, schema: "My Saved Schema", }); } catch (error) { if (error instanceof Mockaroo.errors.InvalidApiKeyError) { console.log("invalid api key"); } else if (error instanceof Mockaroo.errors.UsageLimitExceededError) { console.log("usage limit exceeded"); } else if (error instanceof Mockaroo.errors.ApiError) { console.log("api error: " + error.message); } else { console.log("unknown error: " + error); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.