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

@vodafoneuk/aim-mocking-logger

v1.1.1

Published

Api Interceptor Middleware - localized cache lib and middleware for dalmatian and other api calls

Downloads

607

Readme

AIM - Vodafone Mocking Service

AIM is a mocking middleware that is based on Express and can mock and record APIs. It operates only on the server-side and does not modify the client-side code. Therefore, you don't need to worry if the mocks are different from the production or other environments, as AIM behaves in the same way as your production environment.

The main advantage of using AIM over other tools is that it does not require mapping files or written code to map your request and serve back the mock files. This leads to lower maintenance costs. AIM can automatically detect which mock to return based on the request.


Contents


How AIM works

When you make an API request, it is normally proxied to your back-end server. AIM essentially sits in between. As long as it is disabled, it is not doing anything. Once it is enabled, you have a few options to choose from:

  1. Disabled mode: The application will continue working as usual without AIM.
  2. Recording mode: API requests are allowed as usual, but the returned responses will also be saved and stored in mock files for future mocking.
  3. Mocking mode: API requests going to your back-end server will be stopped, and mocked responses that have been created or recorded previously will be received.

AIM does not allow using both modes simultaneously to avoid confusion about which data is real and which is mocked.

If Mocking mode is enabled, and mocks do not exist, AIM will provide guidelines on how to fix the problem and which files to create, and/or create mocks manually.

AIM is a unique type of middleware because it requires passing the application to it in order to maintain good control over it. If implemented differently, the setup process would be much more complex since AIM needs to proxy requests.

Currently, AIM is only capable of mocking JSON responses. The default response status for mocks is always 200, but it can be changed as needed.

Some of the most important features of AIM:

  1. session: allows multiple people to work on mock files with different data. AIM recognises who you are based on the session of first connect and returns the same in-memory session later on.
  2. ConfigController: provides dynamic configuration inside AIM.
    • All configurations come from it.
    • Different configurations are available for different users (session support).
    • Handles configuration endpoints (health, mocking, recording, etc.) that can be modified by APIs.
  3. Cache = mocks: AIM supports only the cache interface.
  4. [HPM] proxy / setupProxy: onProxyRequest and onProxyResponse are the functions where AIM actually sits and can manipulate requests, responses, and data.
  5. cacheController: helps to return correct mocks.

All mock responses can be recognised via the __cacheMeta object added to the response. Some of its properties can be modified to provide a better and more realistic mocking experience.

"__cacheMeta": {    // used for visualising body and query parameters for debugging purpose, main ingredients for the hash
  "status": 400,    // can be modified
  "delay": 5000,    // property in mocks to delay response time
  "hash": {
    "body": {},
    "query": {}
  }
}

Package structure

AIM is a NX monorepo that includes three packages:

  • Core: the main package where AIM "sits"
  • Logger: a custom-built package that provides AIM-specific logs in the terminal, giving clear information about what is being done
  • Playground: a place where you can test AIM.

Playground

Running yarn start:playground will execute tests and scenarios that showcase how AIM works. You can also import these scenarios into your Postman.

You can import AIM.postman_collection.json in Postman while running the playground to experiment with AIM API via Postman.


Getting started

Requirements

  • Node version >18.13.0
  • Both packages installed: @vodafoneuk/aim-mocking and @vodafoneuk/aim-mocking-logger

Installation

With npm:

npm install @vodafoneuk/aim-mocking @vodafoneuk/aim-mocking-logger

With yarn:

yarn add @vodafoneuk/aim-mocking @vodafoneuk/aim-mocking-logger

Quick Start

Implement into express app

import Aim from '@vodafoneuk/aim-mocking'

import express from 'express'

const app = express()

Aim(app, yourConfig)

Configuration is specific to your project. It is important to remember that it is not dynamic; AIM behaviour is controlled through API calls to AIM itself.

export interface AimConfig {
  /** Debug options */
  debug?: {
    setup?: boolean
    cache?: boolean
    config?: boolean
    autofix?: boolean
    onProxyRequest?: boolean
    onProxyError?: boolean
    onProxyResponse?: boolean
    configEndpoints?: boolean
    cacheController?: boolean
    fileInterface?: boolean
    scenarioList?: boolean
  }
  /** List of ignored paths that are already included in "proxy" config. */
  ignoredPaths?: string[]

  /** Aim internal api endpoints prefix  */
  apisConfigurationEndpointsPrefix?: string

  /** Proxy configuration for paths that AIM should intercept, mock and record */
  proxy: Record<string, AimProxyConfig>

  /** Request body keys that should be ignored when calculating a hash */
  hashIgnoredReqBodyKeys?: string[]

  /** Request query keys that should be ignored when calculating a hash */
  hashIgnoredReqQueryKeys?: string[]

  /** Request url parts that should be ignored when calculating a hash */
  hashIgnoredReqPathPatterns?: string[]

  /** Function to rewrite request url in order to remove some parts from mock file name */
  rewriteMockPathName?: null | ((str: string) => string)

  /** Storage interface to use, only "file" is supported atm */
  storageInterface?: 'file'

  /** Location where the mocks will be stored. It is recommended to not change this value */
  storageInterfaceRootPath?: string
  enableAutofix?: boolean
}

Examples

Below are not default values! If you are unsure of what each option does, please do not copy it.


  AimMiddleware(app, {
    ignoredPaths: [],
    hashIgnoredReqBodyKeys: ['customerId', 'time'],
    hashIgnoredReqQueryKeys: ['perpage'],
    hashIgnoredReqPathPatterns: [],
    rewriteMockPathName: (requestPath: string) => {
      return requestPath.replace(/api\//, '')
    },
    proxy: {
      '/api': {
        // Ask AIM to proxy back to your own server
        // This is useful if you want to use your own proxy instead of AIM
        // which will be removed in production code
        target: 'http://localhost:3000',
        secure: false,
        changeOrigin: true,
      },
    },
  })

Contributing

  • Fork the repository.
  • Make your changes.
  • Send a pull request, ensuring that the application still runs and tests are passing.
  • A member of our team will review and discuss your changes.

Releases

  • Create a PR.
  • Make your changes.
  • Manually prepare the release and release notes.
  • Bump versions of the modified packages.
  • Send a pull request, ensuring that the application still runs and tests are passing.
  • Once merged, new release will be created automatically through publish action.

People

Author: Vodafone UK

Current lead maintainer: Radek Swiat

See all contributors here


License

MIT License

NOTICE