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

@mockoon/serverless

v9.0.0

Published

Mockoon's serverless library. Use Mockoon in serverless environments: AWS Lambda, GCP Functions, Firebase Functions, etc.

Downloads

10,463

Readme

Mockoon's Serverless package provides an easy way to run Mockoon's mock APIs in cloud functions and serverless environments: AWS Lambda, GCP Functions, Firebase Functions, etc.

The Serverless package supports the same features as the main application and CLI (with some limitations, see below): templating system, proxy mode, route response rules, etc.

Using this package

Installation

$ npm install @mockoon/serverless

Mockoon's data file

The Serverless package needs a Mockoon Environment object loaded from a data file. You are responsible for loading this data file (from a URL, S3, etc.) and providing the object to the class constructor (see below).

In the examples below, we will be loading the data file as if it was located next to your function's main file.

Request listener (Express application)

This package exposes a single MockoonServerless class. To create a new RequestListener (an Express application), use the following code:

const mockoon = require('@mockoon/serverless');

// Load the Mockoon Environment object
const mockEnv = require('./datafile.json');

const app = new mockoon.MockoonServerless(mockEnv);

exports.handler = app;

For vendor-specific code, see the sections below.

AWS Lambda

To use Mockoon Serverless in an AWS Lambda, you can use the following code:

const mockoon = require('@mockoon/serverless');

// Load the Mockoon Environment object
const mockEnv = require('./datafile.json');

const mockoonServerless = new mockoon.MockoonServerless(mockEnv);

module.exports.handler = mockoonServerless.awsHandler();

@mockoon/serverless is using the serverless-http package to wrap Mockoon's Express.js API.

Firebase/GCP Functions

To use Mockoon Serverless in a Firebase Function, you can use the following code:

const { onRequest } = require('firebase-functions/v2/https');
const mockoon = require('@mockoon/serverless');

// Load the Mockoon Environment object
const mockEnv = require('./datafile.json');

const app = new mockoon.MockoonServerless(mockEnv).firebaseApp();

exports.app = onRequest(app);

Since Firebase Functions uses GCP Functions underhood, a sighly different approach can be used with the functions-framework-nodejs:

const functions = require('@google-cloud/functions-framework');
const mockoon = require('@mockoon/serverless');

// Load the Mockoon Environment object
const mockEnv = require('./datafile.json');

const app = new mockoon.MockoonServerless(mockEnv).firebaseApp();

functions.http('app', app);

Netlify Functions

To use Mockoon Serverless with Netlify's serverless functions, first create a new Netlify function with the following code:

const mockoon = require('@mockoon/serverless');

// Load the Mockoon Environment object
const mockEnv = require('./datafile.json');

const mockoonServerless = new mockoon.MockoonServerless(mockEnv);

exports.handler = mockoonServerless.netlifyHandler();

If you're not sure how to create a Netlify function, please read their official documentation.

Then, you will need to setup a redirect to direct requests to the mock API. A prefix like api is frequently used to distinguish between the requests targeting hosted websites, from requests targeting the API. Netlify will forward the full path to the running Mockoon serverless function which means that you need the same prefix in your mock configuration. To add this redirection in your netlify.toml you have two possibilities:

[[redirects]]
  force = true
  from = "/api/*"
  status = 200
  to = "/.netlify/functions/{NAME_OF_YOUR_FUNCTION}/api/:splat"

or

[[redirects]]
  force = true
  from = "/api/*"
  status = 200
  to = "/.netlify/functions/{NAME_OF_YOUR_FUNCTION}"

After deploying to Netlify, any request starting with /api/* (e.g. https://APP_NAME.netlify.app/api/endpoint) would match the corresponding route (e.g. /api/endpoint) in your Mockoon config. You can also test locally using the Netlify CLI.

Options

The MockoonServerless class accepts an optional options object as a second parameter. The following options are available:

| Option name | Type | Default value | Description | | --------------------- | ---------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | logTransaction | boolean | false | Enable full transaction logging (see below). | | disabledRoutes | string[] | [] | Disable route(s) by UUID or keyword present in the route's path (do not include a leading slash) or keyword present in a folder name (see below). | | fakerOptions.locale | string | [] | Faker locale (e.g. 'en', 'en_GB', etc. For supported locales, see below.) | | fakerOptions.seed | number | [] | Number for the Faker.js seed (e.g. 1234) | | envVarsPrefix | string | MOCKOON_ | Environment variables prefix. Pass an empty string to disable it. | | enableAdminApi | boolean | true | Enable (default) or disable the Admin API. | | disableTls | boolean | false | Disable TLS. TLS configuration is part of the environment configuration (more info: https://mockoon.com/docs/latest/server-configuration/serving-over-tls/). | | maxTransactionLogs | number | 100 | Maximum number of transaction logs to keep in memory for retrieval via the admin API (default: 100). | | enableRandomLatency | boolean | false | Randomize global and responses latencies between 0 and the specified value (default: false). |

Example:

const mockoonServerless = new mockoon.MockoonServerless(mockEnv, {
  logTransaction: true,
  // disable all routes containing 'users' in their path, and the route with UUID '0999df54-7d57-407e-9325-c18d97fea729'
  disabledRoutes: ['users', '0999df54-7d57-407e-9325-c18d97fea729'],
  fakerOptions: {
    locale: 'en_GB',
    seed: 1234
  },
  envVarsPrefix: 'CUSTOM_PREFIX_',
  enableAdminApi: false,
  disableTls: true,
  enableRandomLatency: false
});

Admin API

Each running mock API has an admin API enabled by default and available at /mockoon-admin/. This API allows you to interact with the running mock API, retrieve logs, and more. You can disable the admin API with the enableAdminApi option.

💡 To learn more about the admin API, check the documentation.

Faker.js options

  • Locale: If not provided, Faker.js will use the default locale: en. For a list of currently supported locales, you can check the supported locales list in Mockoon's commons library. You can also check Faker.js locales list for more information (⚠️ Some locales may not yet be implemented in Mockoon).
  • Seed: If not provided, Faker.js will not use a seed. By providing a seed value, you can generate repeatable sequences of fake data. Using seeding will not always generate the same value but rather a predictable sequence.

Logging

Mockoon's Serverless package logs all server events (start, stop, proxy creation, transactions, etc.) to the console. You can also enable full transaction logging to log all requests and responses (see below).

Transaction logging

When using the logTransaction option, logs will contain the full transaction (request and response) with the same information you can see in the desktop application "Logs" tab.

Example:

{
  "app": "mockoon-server",
  "level": "info",
  "message": "Transaction recorded",
  "timestamp": "YYYY-MM-DDTHH:mm:ss.sssZ",
  "environmentName": "Demo API",
  "environmentUUID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "requestMethod": "GET",
  "requestPath": "/test",
  "requestProxied": false,
  "responseStatus": 200,
  "transaction": {
    "proxied": false,
    "request": {
      "body": "{}",
      "headers": [{ "key": "accept", "value": "*/*" }],
      "method": "GET",
      "params": [],
      "query": "",
      "queryParams": {},
      "route": "/test",
      "urlPath": "/test"
    },
    "response": {
      "body": "{}",
      "headers": [
        { "key": "content-type", "value": "application/json; charset=utf-8" }
      ],
      "statusCode": 200,
      "statusMessage": "OK"
    },
    "routeResponseUUID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "routeUUID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  }
}

To enable full transaction logging, set logTransaction to true in the constructor options:

const mockoonServerless = new mockoon.MockoonServerless(mockEnv, {
  logTransaction: true
});

The transaction model can be found here.

Disabling routes

You can disable routes at runtime by providing their UUIDs or a keyword present in the route's path (do not include a leading slash). You can also disable all the routes present in a folder (including subfolders) by adding a keyword present in a folder name.

This is the counterpart of the "Toggle route" feature in the desktop application (right-click on a route -> "Toggle route").

For example, to disable all routes in a folder named folder1, and all routes having "users" in their paths, you can provide the following array ['folder1', 'users'].

Serverless package limitations

Due to the stateless nature of cloud functions, some of Mockoon's features will not work:

  • the data buckets will not be persisting and be regenerated during each call.
  • the rules based on the request number will not work as this counter will be reset during each call.

Mockoon's documentation

You will find Mockoon's documentation on the official website.

Sponsors

Mockoon is an open-source project built by volunteer maintainers. If you like our application, please consider sponsoring us and join all the Sponsors and Backers who helped this project over time!

Subscribe to Mockoon Cloud

With advanced features for solo developers and teams, Mockoon Cloud supercharges your API development:

Upgrade today and take your API development to the next level.

Support/feedback

You can discuss all things related to Mockoon's CLI, and ask for help, on the official community. It's also a good place to discuss bugs and feature requests before opening an issue on this repository. For more chat-like discussions, you can also join our Discord server.

Contributing

If you are interested in contributing to Mockoon, please take a look at the contributing guidelines.

Please also take a look at our Code of Conduct.

Roadmap

If you want to know what will be coming in the next release you can check the global Roadmap.

New releases will be announced on Mockoon's Twitter account @GetMockoon and through the newsletter to which you can subscribe here.