api-data-seeder
v0.1.0
Published
Seeds test data via sequential API calls when DB access isn't available
Readme
api-data-seeder
Seeds test data via sequential API calls when direct DB access isn't available. Define request chains with {{variable}} interpolation, run them in order, and export results as structured test-data JSON.
Quick Start
npm install api-data-seeder
npx api-data-seeder initEdit .api-data-seeder/seeder.config.ts, then:
ts-node .api-data-seeder/run.tsseeder.config.ts Reference
import { SeederConfig } from 'api-data-seeder';
import { getAuth0Token } from 'api-data-seeder/auth';
const config: SeederConfig = {
// Required. Base API URL prepended to relative request URLs.
baseUrl: process.env.API_BASE_URL!,
// Required. Used to name output files, e.g. successful-requests.dev.json
environment: process.env.ENVIRONMENT!,
// Required. Called once per execute() invocation. Must return a Bearer token.
getToken: () =>
getAuth0Token({
domain: process.env.AUTH0_DOMAIN!,
clientId: process.env.AUTH0_CLIENT_ID!,
clientSecret: process.env.AUTH0_CLIENT_SECRET!,
audience: process.env.AUTH0_AUDIENCE!,
// organization: process.env.AUTH0_ORG, // optional
}),
// Optional. Path to request-bodies.json or a directory of .json files.
// Default: .api-data-seeder/request-bodies.json
requestBodiesPath: '.api-data-seeder/request-bodies.json',
// Optional. Directory where successful/failed request caches are stored.
// Default: .api-data-seeder/output
outputDir: '.api-data-seeder/output',
// Optional. Directory where test-data.{env}.json is exported.
// Default: .api-data-seeder/test-data
testDataExportPath: '.api-data-seeder/test-data',
// Optional. When present, enables mTLS client certificate authentication.
certificates: {
certPath: './certificates/DEV/Client.crt',
keyPath: './certificates/DEV/Client.key',
rejectUnauthorized: true, // default; set to false to skip TLS verification
},
};
export default config;Request Bodies Format
requestBodiesPath points to a single .json file or a directory of .json files. When a directory is given, all .json files are shallow-merged in alphabetical order — duplicate scenario keys: last file wins.
{
"scenarioName": {
"requestName": {
"url": "/some/endpoint",
"method": "POST",
"body": {
"product_id": "{{otherScenario.otherRequest.savedFields.product_id}}"
},
"headers": { "X-Custom": "value" },
"fieldsToSave": ["id", "nested.field"]
}
}
}- Scenarios execute in order; requests within a scenario execute in order.
- A scenario stops at the first failed request (fail-fast).
- Cross-scenario references via
{{scenarioName.requestName.savedFields.field}}. headersare merged with defaults (Authorization,Content-Type); custom values override defaults.fieldsToSavesupports dot-notation paths for nested response fields.
execute() API Reference
import { execute } from 'api-data-seeder';
// Run all scenarios
await execute({ mode: 'all' });
// Run a single scenario
await execute({ mode: 'scenario', scenario: 'myScenario' });
// Retry scenarios that failed in the last run
await execute({ mode: 'retry-failed' });
// Print grouped results to console (no file changes)
await execute({ mode: 'show-results' });
// Manually export cached results to test-data file
await execute({ mode: 'export' });Config is auto-discovered at .api-data-seeder/seeder.config.ts relative to process.cwd().
getToken() is called once at the start of each execute() call. The same token is reused for all scenarios in that invocation.
After all, scenario, and retry-failed modes, test data is auto-exported on success.
Auth0 Helper
import { getAuth0Token } from 'api-data-seeder/auth';
const token = await getAuth0Token({
domain: 'your-tenant.auth0.com',
clientId: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
audience: 'https://your-api/',
organization: 'org_abc123', // optional
});Any async function returning a string works for getToken — Auth0 is not required.
Test Data Export Format
{
"scenarioName": {
"requestName": {
"saved_field": 123
}
}
}Exported to <testDataExportPath>/test-data.<environment>.json.
Certificate Setup (mTLS)
Set certificates in the config:
certificates: {
certPath: path.resolve('./certificates/DEV/Client.crt'),
keyPath: path.resolve('./certificates/DEV/Client.key'),
rejectUnauthorized: false, // only if behind a self-signed CA
}Presence of the certificates key enables mTLS. When the files are not found at the given paths, a warning is logged and requests proceed without a client certificate.
init Command
npx api-data-seeder init scaffolds the .api-data-seeder/ directory:
.api-data-seeder/
├── seeder.config.ts # Config template with Auth0 example
├── run.ts # User-owned entry point
├── request-bodies.json # Example scenario with two requests
├── output/ # Cache dir — add to .gitignore
└── test-data/ # Exported test data destinationThe command fails if .api-data-seeder/ already exists.
Environment Variables
The seeder does not load .env files. Load them yourself before calling execute() (e.g. via dotenv). All env-var reads belong in your seeder.config.ts.
Requirements
- Node.js 20+
ts-node(peer dependency, required at runtime for loadingseeder.config.ts)
