{"id":21009024,"url":"https://github.com/avin/fake-api-middleware","last_synced_at":"2025-05-15T02:32:54.958Z","repository":{"id":65189030,"uuid":"585995582","full_name":"avin/fake-api-middleware","owner":"avin","description":"Express/Connect middleware for returning dummy reponses","archived":false,"fork":false,"pushed_at":"2023-12-04T09:40:58.000Z","size":217,"stargazers_count":10,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-04-26T17:23:13.371Z","etag":null,"topics":["connect","dummies","express","fake","middleware","mock-server"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/avin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2023-01-06T16:51:30.000Z","updated_at":"2023-05-30T16:40:41.000Z","dependencies_parsed_at":"2023-02-10T06:31:16.258Z","dependency_job_id":null,"html_url":"https://github.com/avin/fake-api-middleware","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/avin%2Ffake-api-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/avin%2Ffake-api-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/avin%2Ffake-api-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/avin%2Ffake-api-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/avin","download_url":"https://codeload.github.com/avin/fake-api-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225324104,"owners_count":17456460,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["connect","dummies","express","fake","middleware","mock-server"],"created_at":"2024-11-19T09:15:12.141Z","updated_at":"2024-11-19T09:15:12.803Z","avatar_url":"https://github.com/avin.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Fake-Api-Middleware\n\nThis is an [Express](https://github.com/expressjs/express)+[Connect](https://github.com/senchalabs/connect) middleware for mocking API responses. It can be used with [Vite](https://github.com/vitejs/vite), [Webpack DevServer](https://github.com/webpack/webpack-dev-server), [CreateReactApp](https://github.com/facebook/create-react-app), and many other frameworks that are based on the NodeJS Connect/Express server.\n\n- 🔩 Compatible with [Express](https://github.com/expressjs/express)+[Connect](https://github.com/senchalabs/connect)\n- 🛠️ Write dummy responses with JavaScript/TypeScript\n- 🔥 Hot reloading of dummy responses\n\n## Install\n\n```sh\nnpm install fake-api-middleware\n```\n\n## Usage\n\nCreate a file for storing response dummies. The file can be either in _JavaScript_ or _TypeScript_.\n\n`./apiDummies/index.ts`: \n```ts\nimport { delay } from 'fake-api-middleware';\nimport type { ResponseFunctionParams } from 'fake-api-middleware';\n\nexport default {\n  // The response can be in the form of a normal JavaScript object, which will be returned as JSON with a status code of 200\n  'POST /test': {\n    foo: 'bar'\n  },\n  \n  // The response can be an object, array, string, number or null\n  'GET /api/users': [\n    {id: 1, name: 'Bob'},\n    {id: 2, name: 'Jack'},\n    {id: 3, name: 'Mike'},\n  ],\n  \n  // The response can also be a function that returns a JavaScript object, which will be returned as a JSON response with a status code of 200\n  'POST /api/createUser': ({ body, query, headers, params, req, res }: ResponseFunctionParams) =\u003e {\n    return {\n      message: `User ${body.name} created`\n    };\n  },\n  \n  // It is possible to change the response status code using the `res` object\n  'GET /api/unknown': ({ body, query, headers, params, req, res }: ResponseFunctionParams) =\u003e {\n    res.statusCode = 404;\n    return {\n      message: `Route does not exist`\n    };\n  },\n  \n  // The API path can contain special regular expression syntax. \n  // For more information, please see https://www.npmjs.com/package/path-to-regexp\n  'GET /api/users/:id': ({ body, query, headers, params, req, res }: ResponseFunctionParams) =\u003e {\n    return {\n      message: `User with id ${params.id} is here`\n    };\n  },\n  \n  // It is possible to use asynchronous response functions\n  'GET /api/async': async ({ body, query, headers, params, req, res }: ResponseFunctionParams) =\u003e {\n    await delay(1000);\n    return {\n      message: `Hello!`\n    };\n  },\n  \n  // Alternatively, the response can be a function that manually prepares an HTTP response. \n  // For more information, please see https://nodejs.org/api/http.html#class-httpserverresponse\n  'POST /api/processData': ({ body, query, headers, params, req, res }: ResponseFunctionParams) =\u003e {\n    res.statusCode = 200;\n    res.setHeader('Content-Type', 'application/json');\n    return res.end(\n      JSON.stringify({\n        additional: {\n          body,\n          query,\n          headers,\n          params\n        },\n        message: 'It is response made with ServerResponse',\n      }),\n    );\n  },\n};\n```\n\nSet up the middleware for the HTTP server with the path to the file containing the response dummies. The following example demonstrates using the Connect server, but please check the setup examples below for more options.\n\n`./server.js`:\n```js\nvar connect = require('connect');\nvar http = require('http');\nconst { middleware: fakeApiMiddleware } = require('fake-api-middleware');\n \nvar app = connect();\n\napp.use(\n  fakeApiMiddleware({\n    responsesFile: './apiDummies/index.ts',\n    watchFiles: ['./apiDummies/**/*'],\n    responseDelay: 250,\n    enable: true,\n  }),\n);\n\nhttp.createServer(app).listen(3000);\n```\n\n\n## API\n\nOptions for the middleware:\n\n* `responsesFile`: `string` - Path to the API dummies file.\n* `responses`: `Record\u003cstring, any\u003e` - Pre-defined dummies object (default: `{}`).\n* `watchFiles`: `string|string[]` - Folders/files to watch for updates to reload dummies file (by default, it only watches the single `responsesFile`).\n* `responseDelay`: `number` - Delay in milliseconds for each dummy response (default: `0`).\n* `enable`: `boolean` - Enable/disable middleware (default: `true`).\n\nOptions for the dummy response function:\n\n* `body`: `Record\u003cstring, any\u003e` - Object with parsed body from request.\n* `query`: `Record\u003cstring, any\u003e` - Object with parsed query parameters of the requested URL.\n* `headers`: `Record\u003cstring, any\u003e` - Object with request headers.\n* `params`: `Record\u003cstring, any\u003e` - Object with URL regular expression values.\n* `req`: `IncomingMessage` - Raw Node.js HTTP [IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage) object.\n* `res`: `ServerResponse` - Raw Node.js HTTP [ServerResponse](https://nodejs.org/api/http.html#class-httpserverresponse) object.\n\n## Examples of how to set up the middleware\n\n### Express\n\n```js\nconst express = require('express');\nconst { middleware: fakeApiMiddleware } = require('fake-api-middleware');\n\nconst app = express();\n\napp.use(\n  fakeApiMiddleware({\n    responsesFile: './apiDummies/index.js',\n  }),\n);\n\napp.listen(8080);\n```\n\n### Vite\n\nUse the built-in plugin for vite in the `vite.config.js` file:\n\n```ts\nimport { defineConfig } from 'vite';\nimport { vitePlugin as fakeApiVitePlugin } from 'fake-api-middleware';\n\nexport default defineConfig({\n  plugins: [\n    fakeApiVitePlugin({\n      responsesFile: './apiDummies/index.ts',\n    }),\n  ],\n});\n```\n\n### Create React App\n\nCreate `setupProxy.js` file in the `src` folder with the following content (note that the `apiDummies` folder should be in the root of the project):\n\n```js\nconst { middleware: fakeApiMiddleware } = require('fake-api-middleware');\n\nmodule.exports = function (app) {\n  app.use(\n    fakeApiMiddleware({\n      responsesFile: './apiDummies/index.js',\n    }),\n  );\n};\n```\n\n### Webpack\n\nTo set up the middleware in a webpack configuration, create or modify the `devServer` section and add a `before` rule:\n\n```js\nconst { middleware: fakeApiMiddleware } = require('fake-api-middleware');\n\nmodule.exports = {\n  // ...\n  devServer: {\n    // ...\n    before(app) {\n      app.use(\n        fakeApiMiddleware({\n          responsesFile: './apiDummies/index.js',\n        }),\n      );\n    },\n  },\n  // ...\n};\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Favin%2Ffake-api-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Favin%2Ffake-api-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Favin%2Ffake-api-middleware/lists"}