@vhictor/amockgen
v1.0.8
Published
Zero-config stateful API mocking CLI
Maintainers
Readme
AmockGen
A high-performance, zero-config stateful API mocking CLI and server built for modern TypeScript monorepos.
amockgen parses OpenAPI (v3.x) specifications and instantly spins up a local HTTP mock server paired with interactive documentation, dynamic stateful data generation, request payload validation, and color-coded terminal telemetry.
Features
Zero-Config Developer Workflow: Automatically detects openapi.json or openapi.yaml in your active working directory or bootstraps a ready-to-use template if none exists.
Stateful In-Memory Store: Implements full CRUD persistence across resources (GET, POST, PUT, PATCH, DELETE) during the server lifecycle.
Dynamic Data Engine: Generates realistic, schema-driven mock data powered by @faker-js/faker based on property types, formats, and key-naming heuristics.
Schema Validation: Uses Ajv and ajv-formats to strictly validate incoming POST, PUT, and PATCH request payloads, returning standard 422 Unprocessable Entity responses on schema mismatches.
Interactive Documentation UI: Embeds Stoplight Elements locally at /docs for testing and exploring endpoints.
Hot-Reloading: Monitors OpenAPI specification files for updates and automatically reloads server routes and schemas in real time.
Visual Terminal Telemetry: Built-in ANSI escape sequences format request methods, HTTP status codes, and execution times (in ms) with distinct color highlights.
Installation
Open your frontend directory in terminal and:
Option 1: install package npm i @vhictor/amockgen@latest, then run npx amockgen to start the mock server.
Option 2: Run package using npx @vhictor/amockgen@latest no installation needed.
Usage:
When you run npx @vhictor/amockgen@latest, amockgen:
Resolves openapi.json / openapi.yaml in your current directory.
Serves the interactive API documentation UI at http://localhost:8083/docs.
Sets up mock HTTP endpoints under http://localhost:8083.
Example Log Output
Parsing OpenAPI spec: C:\Users\user\amockgen\openapi.json
┌─────────────────────────────────────────────────────────────┐
│ 🚀 API Mock Server & Documentation Running │
│ │
│ • Interactive Docs: http://localhost:8083/docs │
│ • Mock API Base: http://localhost:8083 │
│ • Spec File: openapi.json │
│ • Status: Active │
└─────────────────────────────────────────────────────────────┘
│ [16:02:12] PUT /todos/0c6dd1a2 - 404 Not Found (6ms)
│ [16:02:17] GET /todos - 200 OK (0ms)
│ [16:03:01] POST /todos - 422 Unprocessable Entity (55ms)
│ [16:03:29] POST /todos - 201 Created (3ms)
For CORS issue
Option 1: Use Next.js API Routes / Route Handlers (Recommended)
Because CORS is a restriction that happens only inside the browser, a backend server can talk to another backend server without any CORS blocks.You can create a small "proxy" route inside Next.js that fetches the external data on the server side and forwards it to your frontend.
If using the App Router (app/ directory):Create a file at app/api/external-data/route.js (or .ts):
import { NextResponse } from 'next/server';
export async function GET() {
const externalApiUrl = 'https://external-service.com';
try {
// 1. Fetch data server-to-server (No CORS restrictions apply here!)
const response = await fetch(externalApiUrl, {
headers: {
'Authorization': `Bearer ${process.env.API_SECRET_KEY}` // Bonus: Safe place to hide keys!
}
});
if (!response.ok) {
return NextResponse.json({ error: 'Failed to fetch external data' }, { status: response.status });
}
const data = await response.json();
// 2. Return the data to your frontend
return NextResponse.json(data);
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}How to call it in your Frontend Component: Now, in your component's useEffect or inside your component logic, fetch from your own local API route instead of the third-party URL:
useEffect(() => {
// Points to your local Next.js Route Handler
fetch('/api/external-data')
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.error(err));
}, []);Option 2: Rewrite the URL in next.config.js
If you don't want to create an explicit API route file, you can instruct Next.js to automatically map a local URL path to the external URL using Rewrites. This makes the browser think the external API is hosted directly on your domain.Open your next.config.mjs (or next.config.js) file and add the rewrites configuration:
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
{
source: '/api/external/:path*', // The path you will call on your frontend
destination: 'https://external-service.com*', // The real external API URL
},
];
},
};
export default nextConfig;Note: Make sure to restart your Next.js development server (npm run dev) after changing this file.
How to call it in your Frontend Component:
useEffect(() => {
// Next.js automatically rewrites this behind the scenes to:
// 'https://external-service.com'
fetch('/api/external/products')
.then((res) => res.json())
.then((data) => console.log(data));
}, []);Option 3: Server Components (No useEffect needed!) If you are using the Next.js App Router, you can often skip useEffect, useState, and client-side fetches entirely by making your component an async Server Component. Data is fetched securely on the server before the HTML is sent to the client.
// app/products/page.js
// This runs entirely on the server. Zero CORS issues, zero useEffect hooks.
async function getProducts() {
const res = await fetch('https://external-service.com');
if (!res.ok) throw new Error('Failed to fetch data');
return res.json();
}
export default async function ProductsPage() {
const products = await getProducts();
return (
<main>
<h1>Products</h1>
{/* Render your data directly */}
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</main>
);
}Tech Stack
Server Framework: Fastify
OpenAPI Parser: @apidevtools/swagger-parser
Validation Engine: Ajv + ajv-formats
Data Mocking: @faker-js/faker
CLI Engine: Commander
File Watcher: Chokidar
Monorepo Tooling: pnpm workspaces + Turborepo
License:
MIT
