New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

loco-server

Package Overview
Dependencies
Maintainers
0
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

loco-server

HTTP Proxy and/or mockup server

  • 4.0.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
28
increased by27.27%
Maintainers
0
Weekly downloads
 
Created
Source

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 <config_file>

or if used in package.json scripts:

loco <config_file>

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
}
FieldDescription
appPortPort to run the server on
appHostHost to run the server on
functionsPathGlob to where to look for loco functions
envFile.env file name with path
reloadOnRequestFlag should funtions be reload on each request which will function as live-reload
optionsRequestHeadersResponse headers for OPTIONS request
optionsRequestStatusCodeOPTIONS 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:

ArgumentDescriptions
reqfull express request object
queryGET query requested represented as JSON, example: {"query":"test"}
bodyJSONPOST body requested as as JSON, example: {"login":"john"}
reqMethodRequest method as a string, example: GET
locoobject containing predefined helper function, described below in the function helpers section
envVarsenvironment variables from the .env file defined in the config
pathsarray 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}
}
KeyValue
statusCoderesponse status code
headersobject containig response header as key and header value as value
bodyresponse 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 :)

paypal

Keywords

FAQs

Package last updated on 13 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc