{"library":"mocker-api","title":"Mocker API for RESTful Development","description":"mocker-api is a development utility designed for mocking RESTful APIs, facilitating frontend development by enabling work independent of a live backend. It supports flexible integration as middleware with common development servers like Express.js and webpack-dev-server. The current stable version is 4.0.0, which has updated its Node.js requirement to `>=16.0.0`. The library features hot module replacement for mock files, allows quick API configuration via JSON or JavaScript files, and provides simple mock API proxying. It also offers first-class TypeScript type definitions for an enhanced developer experience. Unlike some other mocking solutions, `mocker-api` can be used independently without relying on a full webpack setup, making it versatile for various project types, including Create React App. It helps streamline development workflows by providing predictable API responses during the early stages of a project.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install mocker-api"],"cli":null},"imports":["import apiMocker from 'mocker-api';","import type { MockerAPIOptions } from 'mocker-api';","// In mocker/index.ts:\ninterface User { id: number; name: string; }\nconst mocks: Record<string, User | User[]> = {\n  'GET /api/users': [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }],\n  'GET /api/user/:id': (req, res) => {\n    const id = parseInt(req.params.id, 10);\n    if (id === 1) return res.json({ id: 1, name: 'Alice' });\n    if (id === 2) return res.json({ id: 2, name: 'Bob' });\n    res.status(404).json({ message: 'User not found' });\n  },\n};\nexport default mocks;"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import express from 'express';\nimport path from 'path';\nimport apiMocker from 'mocker-api';\n\ninterface User { id: number; name: string; email: string; }\n\n// --- Create 'mocker/index.ts' file in your project root or source directory ---\n// const mocks = {\n//   'GET /api/users': [\n//     { id: 1, name: 'Alice', email: 'alice@example.com' },\n//     { id: 2, name: 'Bob', email: 'bob@example.com' },\n//   ],\n//   'POST /api/users': (req, res) => {\n//     const newUser: User = { id: Date.now(), ...req.body };\n//     console.log('New user created:', newUser);\n//     res.status(201).json(newUser);\n//   },\n//   'GET /api/user/:id': (req, res) => {\n//     const userId = parseInt(req.params.id, 10);\n//     const users: User[] = [\n//       { id: 1, name: 'Alice', email: 'alice@example.com' },\n//       { id: 2, name: 'Bob', email: 'bob@example.com' },\n//     ];\n//     const user = users.find(u => u.id === userId);\n//     if (user) {\n//       res.json(user);\n//     } else {\n//       res.status(404).json({ message: `User with ID ${userId} not found` });\n//     }\n//   },\n//   'GET /api/posts': [\n//     { id: 101, title: 'First Post' },\n//     { id: 102, title: 'Second Post' },\n//   ],\n//   // Example of proxying specific requests: anything starting with /github/\n//   'GET /github/*': 'https://api.github.com/',\n// };\n// export default mocks;\n// -----------------------------------------------------------------------------\n\nconst app = express();\nconst port = process.env.PORT ?? 8080; // Use process.env.PORT or default to 8080\n\n// Enable JSON body parsing for POST/PUT requests (essential for 'POST /api/users' mock)\napp.use(express.json());\n\n// Resolve the path to your mock definition file.\n// Ensure 'mocker/index.js' or 'mocker/index.ts' exists and exports the mock definitions.\nconst mockDirectory = path.resolve(__dirname, 'mocker/index.js'); // Adjust for your build output\n\napiMocker(app, mockDirectory, {\n  // Optional: Enable proxying for unmocked routes. Requests matching '/api/(.*)'\n  // that are not explicitly mocked will be forwarded to JSONPlaceholder.\n  proxy: {\n    '/api/(.*)': 'https://jsonplaceholder.typicode.com/', \n  },\n  // Set changeHost to true when proxying to external hosts like GitHub API to avoid CORS issues.\n  changeHost: true,\n  // Optional: Simulate network delay for all mock responses in milliseconds.\n  delay: 500,\n});\n\napp.listen(port, () => {\n  console.log(`Mock API Server is running at http://localhost:${port}`);\n  console.log('Try visiting:');\n  console.log(`- http://localhost:${port}/api/users (mocked data from 'mocker/index.ts')`);\n  console.log(`- http://localhost:${port}/api/user/1 (mocked data from 'mocker/index.ts')`);\n  console.log(`- http://localhost:${port}/api/todos/1 (proxied to JSONPlaceholder)`);\n  console.log(`- http://localhost:${port}/github/users/jaywcjlove (proxied to GitHub API)`);\n});","lang":"typescript","description":"This quickstart sets up a basic Express server and integrates `mocker-api` as middleware. It demonstrates defining mock API routes in a separate file (e.g., `mocker/index.ts`), handling both static JSON responses and dynamic request/response logic, and includes an example of proxying unmocked requests to a real API like JSONPlaceholder or GitHub for a seamless development experience.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}