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

openapi-mock-express-middleware

v4.1.1

Published

Generates express mock-servers from OpenAPI specs

Downloads

3,590

Readme

npm Build Status codecov size

openapi-mock-express-middleware

Generates express mock-servers from Open API 3.0 specs.

Installation

To begin, you'll need to install openapi-mock-express-middleware:

$ npm install openapi-mock-express-middleware --save-dev

Usage

Simple Config

const express = require('express');
const { createMockMiddleware } = require('openapi-mock-express-middleware');

const app = express();

app.use(
  '/api', // root path for the mock server
  createMockMiddleware({ spec: '/absolute/path/to/your/openapi/spec.yml' }),
);

app.listen(80, () => console.log('Server listening on port 80'));

Advanced Config

The middleware uses json-schmea-faker under the hood. To configure it, you can pass the options object to the factory function. (The full list of available options can be seen here)

const express = require('express');
const { createMockMiddleware } = require('openapi-mock-express-middleware');

const app = express();

app.use(
  '/api',
  createMockMiddleware({
    spec: '/absolute/path/to/your/openapi/spec.yml', // string or OpenAPIV3.Document object
    options: { // json-schema-faker options
      alwaysFakeOptionals: true,
      useExamplesValue: true,
      // ...
    },
    configure: (jsf) => {
    	// function where you can extend json-schema-faker
    	...
    }
  }),
);

app.listen(80, () => console.log('Server listening on port 80'));

Mock data

Basic behavior

By default midleware generates random responses depending on the types specified in the openapi docs.

doc.yml

...
paths:
  /company
    get:
      responses:
        '200':
          content:
            application/json:
              schema:
                type: object
                required:
                  - id
                  - number
                properties:
                  id:
                    type: string
                  number:
                type: integer
...

GET /company response

{
  id: 'dolor veniam consequat laborum',
  number: 68385409.
}

Faker or Chance generated responses

In addition faker.js or chance.js methods can be specified for data generation. In order to use these generators you have to configure middleware through the configure option of the factory function.

const express = require('express');
const { createMockMiddleware } = require('openapi-mock-express-middleware');
import faker from '@faker-js/faker';
import Chance from 'chance';

const app = express();

app.use(
  '/api',
  createMockMiddleware({
    spec: '/absolute/path/to/your/openapi/spec.yml',
    configure: (jsf) => {
    	jsf.extend('faker', () => faker);
	jsf.extend('chance', () => new Chance());
    }
  }),
);

app.listen(80, () => console.log('Server listening on port 80'));

After that you can use 'x-faker' and/or 'x-chance' attributes in your openapi specs.

spec.yml

...
paths:
  /user
    get:
      responses:
        '200':
          content:
            application/json:
              schema:
                type: object
                required:
                  - id
                  - name
                properties:
                  id:
                    type: string
                    x-faker: random.uuid
                  name:
                    type: string
                    x-faker: name.findName
                  email:
                    type: string
                    x-chance:
                      email:
                        domain: fake.com	  
...

GET /user response

{
  id: '8c4a4ed2-efba-4913-9604-19a27f36f322',
  name: 'Mr. Braxton Dickens',
  email: '[email protected]'
}

Responses generated from examples

If an example for the response object is specified, it will be used as a resulting sever response.

doc.yml

...
paths:
  /user
    get:
      responses:
        '200':
          content:
            application/json:
              schema:
                type: object
                example:
                  id: 'id-125'
                  name: 'John Smith'
                required:
                  - id
                  - name
                properties:
                  id:
                    type: string
                    x-faker: random.uuid
                  name:
                    type: string
                    x-faker: name.findName
...

GET /user response

{
  id: 'id-125',
  name: 'John Smith'.
}

If multiple examples for the response object are specified, the first one will be used as a resulting sever response.

doc.yml

...
paths:
  /user
    get:
      responses:
        '200':
          content:
            application/json:
              schema:
                type: object
                examples:
                  first:
                    value:
                      id: 'id-125'
                      name: 'John Smith'
                  second:
                    value:
                      id: 'some-other-id'
                      name: 'Joe Doe'
                required:
                  - id
                  - name
                properties:
                  id:
                    type: string
                    x-faker: random.uuid
                  name:
                    type: string
                    x-faker: name.findName
...

GET /user response

{
  id: 'id-125',
  name: 'John Smith'.
}

If you want to use some other logic for generating responses from the examples attributes you can easily implement it by overwriting this behavior in the configure option of the middleware's factory function:

const express = require('express');
const { createMockMiddleware } = require('openapi-mock-express-middleware');

const app = express();

app.use(
  '/api',
  createMockMiddleware({
    spec: '/absolute/path/to/your/openapi/spec.yml',
    configure: (jsf) => {
      jsf.define('examples', (value) => {
        if (typeof value === 'object' && value !== null && Object.keys(value).length) {
          return value[Object.keys(value)[0]].value;
        }

        return '';
      });
    }
  }),
);

app.listen(80, () => console.log('Server listening on port 80'));

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT