https://github.com/marcinrek/loco-server
HTTP Proxy and/or mockup server
https://github.com/marcinrek/loco-server
express mockup proxy server
Last synced: about 1 month ago
JSON representation
HTTP Proxy and/or mockup server
- Host: GitHub
- URL: https://github.com/marcinrek/loco-server
- Owner: marcinrek
- Created: 2022-02-26T11:28:24.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2023-11-22T12:51:32.000Z (almost 2 years ago)
- Last Synced: 2024-07-09T13:30:53.941Z (about 1 year ago)
- Topics: express, mockup, proxy, server
- Language: JavaScript
- Homepage:
- Size: 188 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Loco
Loco is a http proxy and/or mockup server.## Features
* forward a request using node-fetch
* mock API response
* supports using .env variables## Changelog
- 4.0.3
- function files can now have .js or .cjs extenstion
- 4.0.2
- fix typo in docs
- 4.0.0
- add an option to load functions on each request so that it is not required to reload the app on a function file change/add/remove. It does require updating the config by adding reloadOnRequest key and setting it to true
- change require node version to v18.16.0
- 3.2.0
- make PUT,PATCH and DELETE requests available
- support wildcard requests like /{function_name}/{id}/{something} - /{id}/{something} will be available as an array [\{id\}, \{something\}] in param.paths
- 3.1.0
- add multer middleware for multipart/form-data support
- 3.0.0
- change process function to only have one parameter now called 'param'.
- change config _functionsPath_ to be an array of glob entries instead of just one
- 2.0.0
- add live reload for function files
- additional loco helper - loco.requireUncached('path');
- additional loco helper - loco.chalk;
- config _functionsDir_ replace with _functionsPath_ which is a glob
- 1.1.1
- fix loco.corsHeaders() error when no headersOverwrites provided
- 1.1.0
- pass reqMethod to processFunction to distinguish type of request if required
- add OPTIONS request support
- enable ovewriting headers in loco.corsHeaders() helper## Installation
```
npm install -sD loco-server
```## Usage
Straight from the command line:
```
npx loco
```
or if used in package.json scripts:
```
loco
```## Configuration
Sample config file:
```
{
"appPort": 8888,
"appHost": "127.0.0.1",
"functionsPath": ["loco_functions/*.js"],
"envFile": ".env",
"reloadOnRequest": true,
"optionsRequestHeaders": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "*"
},
"optionsRequestStatusCode": 200
}
```| Field | Description |
|---|---|
| appPort | Port to run the server on |
| appHost | Host to run the server on |
| functionsPath | Glob to where to look for loco functions |
| envFile | .env file name with path |
| reloadOnRequest | Flag should funtions be reload on each request which will function as live-reload |
| optionsRequestHeaders | Response headers for OPTIONS request |
| optionsRequestStatusCode | OPTIONS request status code |## Functions
Functions are understood as JS files specified by _functionsPath_ in the configuration. Each file will be served under a separate webpath in the server. This webpath is equal to the file namie without _.js_ extension.Function file scaffold:
```
/**
* Function description string
*/
const description = 'Blank function scaffold.';/**
* Main process function
* @param {object} param.req entire request object
* @param {object} param.query GET request query
* @param {object} param.bodyJSON POST request body
* @param {string} param.reqMethod request method
* @param {object} param.loco helper functions object
* @param {object} param.envVars environment variables
* @param {array} param.paths array of wildcard paths
* @returns {object} response object consisting of response statusCode, body and headers object
*/
const processFunction = async (param) => {
return {
statusCode: 200,
headers: param.loco.corsHeaders(),
body: {mockup: true}
};
};// Export
module.exports = {
processFunction,
description,
};```
The _descriptions_ const is used for providing a short summary of a given function.
Main required function in each function file is the _processFunction_.
It has one parameter called param which is an object containing:
| Argument | Descriptions |
|---|---|
| req | full express request object |
| query | GET query requested represented as JSON, example: ```{"query":"test"}``` |
| bodyJSON | POST body requested as as JSON, example: ```{"login":"john"}``` |
| reqMethod | Request method as a string, example: ```GET```|
| loco | object containing predefined helper function, described below in the function helpers section|
| envVars | environment variables from the .env file defined in the config |
| paths | array of paths that were used when this is a wildcard request |The function must return an object with a given structure:
```
{
statusCode: 200,
headers: param.loco.corsHeaders(),
body: {mockup: true}
}
```
| Key| Value |
|---|---|
| statusCode | response status code |
| headers | object containig response header as key and header value as value |
| body | response body |## Function helpers
Current list of helpers passed as a _param.loco_ argument to the _processFunction_
* ```param.loco.fetchJSON(url:string, options:object)``` - node-fetch module
* ```param.loco.returnJsonWithDelay(sec, jsonResponse)``` - usefull when a mocked response is return to fake a time delay. Example usage:
```
return {
[...]
body: await loco.returnJsonWithDelay(3, jsonData),
};
```
this will return _jsonData_ after 3 seconds.
* ```loco.corsHeaders(headersOverwrites)``` - returns headers that can be used when you want to enable cors:
```
{
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-type',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
}
```
Example usage:
```
return {
[...]
headers: param.loco.corsHeaders(),
[...]
};
```
You can also overwrite a default header or add a new one:
```
headers: param.loco.corsHeaders({"Content-Type": "text/html; charset=utf-8"}),
```
* ```loco.fetchJSON(url:string, options:object)``` - utility function to make a fetch request to an endpoint that returns JSON response. Example usage:
```
const jsonData = await param.loco.fetchJSON('https://api.url/', {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(param.bodyJSON.payload)
}).catch((err) => {
return {error: err.message};
});
[...]
return {
[...]
body: jsonData,
};
```
* ```param.loco.requireUncached(path)``` - clear cache for _path_ and then require. Usefull when you modify data in processFunction often.## Donate
If you find this piece of code to be useful, please consider a donation :)[](https://www.paypal.com/donate?hosted_button_id=ZPSPDRNU99V4Y)