Skip to content

TEE2DWHY/api-mocker

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

@cwt-build/api-mocker

Lightweight API mocking tool with realistic data generation for frontend development

Built by Create With Tech (CWT) - Empowering developers with practical tools.

🎯 Features

  • Smart Data Generation: Auto-generates realistic mock data based on field types
  • Stateful by Default: POST creates, GET retrieves, PUT updates, DELETE removes - maintains state across requests
  • Zero Config for Common Patterns: Pagination, filtering, and sorting work out of the box
  • TypeScript First: Full type safety and IntelliSense support
  • Minimal Setup: Get started with just a schema definition
  • Realistic Delays: Simulate network latency for more realistic development

πŸ“¦ Installation

npm install @cwt-build/api-mocker

or

yarn add @cwt-build/api-mocker

πŸš€ Quick Start

import { createMockAPI } from '@cwt-build/api-mocker';

// Define your API structure
const api = createMockAPI({
  '/users': {
    schema: {
      id: 'uuid',
      name: 'fullName',
      email: 'email',
      age: 'number',
      city: 'city',
    },
    count: 50, // Generate 50 users
  },
});

// Use it like a real API
const response = await api.get('/users', { page: 1, limit: 10 });
console.log(response.data);

πŸ“– Usage Examples

Basic CRUD Operations

// GET all resources (with pagination)
const users = await api.get('/users', {
  page: 1,
  limit: 10,
});

// GET single resource by ID
const user = await api.getById('/users', 'user-id-123');

// POST - Create new resource
const newUser = await api.post('/users', {
  name: 'John Doe',
  email: '[email protected]',
});

// PUT - Update resource
const updated = await api.put('/users', 'user-id-123', {
  name: 'Jane Doe',
});

// DELETE - Remove resource
const deleted = await api.delete('/users', 'user-id-123');

Pagination & Sorting

// Paginated results
const response = await api.get('/products', {
  page: 2,
  limit: 20,
});

// Sorted results
const sorted = await api.get('/products', {
  sort: 'price',
  order: 'asc', // or 'desc'
});

// Response includes metadata
console.log(response.data);
// {
//   data: [...],
//   meta: {
//     page: 1,
//     limit: 10,
//     total: 50,
//     totalPages: 5
//   }
// }

Multiple Endpoints

const api = createMockAPI({
  '/users': {
    schema: { id: 'uuid', name: 'fullName', email: 'email' },
    count: 100,
  },
  '/products': {
    schema: {
      id: 'uuid',
      name: 'string',
      price: 'price',
      description: 'description',
    },
    count: 50,
  },
  '/orders': {
    schema: {
      id: 'uuid',
      userId: 'uuid',
      productId: 'uuid',
      date: 'date',
    },
    count: 200,
  },
});

Custom Seed Data

const api = createMockAPI({
  '/categories': {
    schema: { id: 'uuid', name: 'string' },
    seed: [
      { id: '1', name: 'Electronics' },
      { id: '2', name: 'Clothing' },
      { id: '3', name: 'Food' },
    ],
  },
});

Network Delay Simulation

const api = createMockAPI(
  {
    '/users': {
      schema: { id: 'uuid', name: 'fullName' },
      count: 50,
    },
  },
  {
    baseDelay: 500, // 500ms delay
    randomDelay: true, // Randomize delay (0-500ms)
  },
);

πŸ”§ Available Data Types

Type Example Output Description
uuid "a1b2c3d4-..." UUID v4
string "lorem" Random word
number 742 Random integer (1-1000)
boolean true Random boolean
email "[email protected]" Realistic email
fullName "John Doe" Full name
firstName "John" First name
lastName "Doe" Last name
date "2024-01-15T..." ISO date string
url "https://..." URL
phone "555-1234" Phone number
address "123 Main St" Street address
city "New York" City name
country "United States" Country name
company "Tech Corp" Company name
jobTitle "Software Engineer" Job title
description "Lorem ipsum..." Paragraph of text
price 29.99 Price (number)
image "https://..." Image URL

πŸ› οΈ API Reference

createMockAPI(config, options?)

Creates a new mock API instance.

Parameters:

  • config: Object defining endpoints and their schemas
  • options (optional):
    • baseDelay: Base delay in milliseconds (default: 0)
    • randomDelay: Randomize delay (default: false)

Returns: MockAPI instance

MockAPI Methods

get(endpoint, params?)

Get all resources from an endpoint.

Parameters:

  • endpoint: The API endpoint (e.g., /users)
  • params (optional):
    • page: Page number (for pagination)
    • limit: Items per page
    • sort: Field to sort by
    • order: 'asc' or 'desc'
    • Any other key for filtering

Returns: Promise<MockResponse>

getById(endpoint, id)

Get a single resource by ID.

Returns: Promise<MockResponse>

post(endpoint, body)

Create a new resource.

Returns: Promise<MockResponse>

put(endpoint, id, body)

Update an existing resource.

Returns: Promise<MockResponse>

delete(endpoint, id)

Delete a resource.

Returns: Promise<MockResponse>

reset(endpoint?)

Reset data for an endpoint (or all endpoints if no argument).

getAllData(endpoint)

Get raw data array for inspection/debugging.

πŸ’‘ Use Cases

  • Frontend Development: Build UI components before backend is ready
  • Demos & Presentations: Quickly create realistic demo data
  • Testing: Generate consistent test data for integration tests
  • Prototyping: Rapidly prototype applications with working data
  • Tutorials: Create educational content with working examples

πŸŽ“ Learn More

This package is part of the CWT ecosystem. Check out more resources:

  • Website: cwt.build
  • Tutorials: Find step-by-step guides on our platform
  • Support: Open an issue on GitHub

πŸ“„ License

This project is licensed under the CWT Protected Open Source License v1.0 - a custom license designed to protect Create With Tech's intellectual property while allowing legitimate use.

Quick Summary

βœ… You CAN:

  • Use it in your projects (personal or commercial)
  • Modify it for your needs
  • Learn from the code
  • Share it with proper attribution

❌ You CANNOT:

  • Republish it as your own package
  • Remove CWT attribution
  • Use CWT branding on derivatives
  • Claim you created it

See the LICENSE file for complete terms.

Questions? [email protected]

πŸ› Found a Bug?

If you find a bug or have a feature request, please open an issue on our GitHub repository.


Made with ❀️ by CWT - Teaching, Building, Innovating

About

Lightweight API mocking for frontend developers. Generate realistic mock data instantly with zero config.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 77.1%
  • JavaScript 22.9%