Skip to content

Selteve/json-api-mocker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

24 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

JSON API Mocker

A lightweight and flexible mock server that uses JSON configuration to quickly create RESTful APIs.

npm version license downloads

✨ Features

  • πŸš€ Quick setup with JSON configuration
  • πŸ”„ Support for GET, POST, PUT, DELETE methods
  • πŸ“ Automatic data persistence
  • πŸ” Built-in pagination support
  • πŸ›  Customizable response schemas
  • 🎭 Integration with Mock.js for powerful data mocking
  • πŸ“€ File upload support
  • πŸ”Œ Real-time communication with WebSocket
  • πŸ’‘ TypeScript support

πŸ“¦ Installation

# Using npm
npm install json-api-mocker

# Using yarn
yarn add json-api-mocker

# Using pnpm
pnpm add json-api-mocker

πŸš€ Quick Start

1. Create Configuration File

Create a data.json file in your project root:

{
  "server": {
    "port": 8080,
    "baseProxy": "/api"
  },
  "routes": [
    {
      "path": "/users",
      "methods": {
        "get": {
          "type": "array",
          "pagination": {
            "enabled": true,
            "pageSize": 10,
            "totalCount": 100
          },
          "response": [
            {
              "id": 1,
              "name": "John",
              "age": 30,
              "city": "New York"
            }
          ]
        }
      }
    },
    {
      "path": "/upload/avatar",
      "methods": {
        "post": {
          "type": "object",
          "mock": {
            "enabled": true,
            "template": {
              "success": true,
              "message": "Upload successful",
              "data": {
                "url": "@image('200x200')",
                "filename": "@string(10).jpg",
                "size": "@integer(1000, 1000000)"
              }
            }
          }
        }
      }
    }
  ]
}

2. Start the Server

There are several ways to start the mock server:

# Method 1: Using npx (Recommended)
npx json-api-mocker

# Method 2: Using npx with a custom config file
npx json-api-mocker ./custom-config.json

# Method 3: If installed globally
json-api-mocker

# Method 4: If installed as a project dependency
# Add this to your package.json scripts:
{
  "scripts": {
    "mock": "json-api-mocker"
  }
}
# Then run:
npm run mock

Now your mock server is running at http://localhost:8080!

You'll see output like this:

Mock Server is running:
- Address: http://localhost:8080
- Base Path: /api
Available APIs:
  GET http://localhost:8080/api/users
  POST http://localhost:8080/api/users
  POST http://localhost:8080/api/upload/avatar

πŸ“– Configuration Guide

For detailed configuration options, please refer to CONFIG.md.

Server Configuration

The server section configures basic server settings:

{
  "server": {
    "port": 8080,      // Server port number
    "baseProxy": "/api" // Base path for all routes
  }
}

Route Configuration

Each route can support multiple HTTP methods:

{
  "path": "/users",    // Route path
  "methods": {
    "get": {
      "type": "array", // Response type: "array" or "object"
      "pagination": {  // Optional pagination settings
        "enabled": true,
        "pageSize": 10,
        "totalCount": 100
      },
      "response": []   // Response data
    },
    "post": {
      "requestSchema": {  // Request body validation schema
        "name": "string",
        "age": "number"
      },
      "response": {
        "success": true
      }
    }
  }
}

File Upload Support

You can configure file upload endpoints in your data.json:

{
  "path": "/upload/avatar",
  "methods": {
    "post": {
      "type": "object",
      "mock": {
        "enabled": true,
        "template": {
          "success": true,
          "message": "Upload successful",
          "data": {
            "url": "@image('200x200')",
            "filename": "@string(10).jpg",
            "size": "@integer(1000, 1000000)"
          }
        }
      }
    }
  }
}

Example Usage:

# Upload single file
curl -X POST http://localhost:8080/api/upload/avatar \
  -H "Content-Type: multipart/form-data" \
  -F "avatar=@/path/to/your/image.jpg"

# Upload multiple files
curl -X POST http://localhost:8080/api/upload/images \
  -H "Content-Type: multipart/form-data" \
  -F "images=@/path/to/image1.jpg" \
  -F "images=@/path/to/image2.jpg"

For detailed configuration options, please refer to CONFIG.md.

🎯 API Examples

Basic CRUD Operations

Get Users List

curl http://localhost:8080/api/users

Get Single User

curl http://localhost:8080/api/users/1

Create User

curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","age":25,"city":"Boston"}'

Update User

curl -X PUT http://localhost:8080/api/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","age":26,"city":"Boston"}'

Delete User

curl -X DELETE http://localhost:8080/api/users/1

Advanced Usage

Pagination

# Get page 2 with 10 items per page
curl http://localhost:8080/api/users?page=2&pageSize=10

Custom Response Headers

The server automatically adds these headers:

  • X-Total-Count: Total number of items (for paginated responses)

πŸ”§ Advanced Configuration

Dynamic Routes

You can use URL parameters in routes:

{
  "path": "/users/:id/posts",
  "methods": {
    "get": {
      "type": "array",
      "response": []
    }
  }
}

Request Validation

Add schema validation for POST/PUT requests:

{
  "requestSchema": {
    "name": "string",
    "age": "number",
    "email": "string"
  }
}

WebSocket Support

You can configure WebSocket endpoints in your data.json:

{
  "websocket": {
    "enabled": true,
    "path": "/ws",
    "events": {
      "realtime-data": {
        "mock": {
          "enabled": true,
          "interval": 5000,  // Send data every 5 seconds
          "template": {
            "timestamp": "@datetime",
            "value|1-100": 1,
            "status|1": ["normal", "warning", "error"]
          }
        }
      },
      "user-status": {
        "mock": {
          "enabled": true,
          "template": {
            "userId|+1": 1,
            "status|1": ["online", "offline", "away"],
            "lastActive": "@datetime"
          }
        }
      }
    }
  }
}

Client Usage Example:

// Connect to WebSocket server
const ws = new WebSocket('ws://localhost:8080/ws');

// Handle connection open
ws.onopen = () => {
  console.log('Connected to WebSocket server');
  
  // Request real-time data
  ws.send(JSON.stringify({
    event: 'realtime-data'
  }));
};

// Handle incoming messages
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
  // {
  //   event: 'realtime-data',
  //   data: {
  //     timestamp: '2024-01-01 12:00:00',
  //     value: 75,
  //     status: 'normal'
  //   }
  // }
};

// Handle errors
ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

// Handle connection close
ws.onclose = () => {
  console.log('Disconnected from WebSocket server');
};

Features:

  • Event-based communication
  • Automatic data sending at specified intervals
  • Mock.js template support for dynamic data
  • Multiple event handlers

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

MIT Β© [Xiong Haiyin]

πŸ™ Acknowledgments

  • Express.js for the excellent web framework
  • All our contributors and users

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published