npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

loco-server

v4.0.3

Published

HTTP Proxy and/or mockup server

Downloads

275

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

| 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 :)

paypal