mock APIs, intelligently, with context, and perform other stuff as well

Overview

@sasta-sa/project

mock APIs, intelligently, with context, and perform other stuff as well 😄

Setting up

  • Clone the project git clone https://github.com/YashKumarVerma/maya-mvp and cd maya-mvp to open it
  • Instal the dependencies with npm i
  • Start development server with nodemon

Triggers

Triggers are like functions, which are called by other triggers or routes. The main aim is to perform database operations / network calls before/after the route has been executed. Use them to run tasks after something happened.

Example usage

  1. Banking
    • you make a request to the bank to collect money via UPI, bank returns OK, accepted, and starts processing.
    • other user can take upto 15 minutes to accept/decline the UPI request
    • bank send back a webhook to your server whether the operation was successful or not.
    • the webhook is a trigger, which runs after your route sends OK

Anatomy of triggers

interface IMayaTriggerDefinition {
    // environment configuration of the http processor
    // added by processor, user DOES NOT pass this
    environment?: IEnvironment,


    // object containing prompts to make to user when trigger being processed
    // if autonomous is true, default values are used
    // passed by user
    prompt?: {
        name: "Yash Kumar Verma",
        age: 21
    }


    // unique identifier for the trigger, used to call other triggers
    // passed by user
    name: string | ContextualFunction<IContext, string>


    // one of the HTTP method
    // passed by user
    method: Method


    // URL for the HTTP request, or function which returns a string
    // passed by user
    url: string | ContextualFunction<IContext, string>


    // header for HTTP request, record<String, string> or function which returns the same
    // passed by user
    header?: IHeader | ContextualFunction<IContext, IHeader>


    // http body sent as payload, can be a contextual function which returns an object
    // passed by user
    body?: any | ContextualFunction<IContext, any>


    // function to run on data returned after HTTP request
    // passed by user
    response?: (
        // instance of environment configurations
        environment: {},
        
        // data collected from user prompt, or defaults if autonomous is true
        prompt: {},
        
        // full configuration of the trigger object 
        trigger: {},

        // complete HTTP response object
        response: {}
    ) => {}


    // names of triggers to run before and after current trigger 
    // passed by user
    before?: Array<string>
    after?: Array<string>


    // setting true will force default values for prompt variables
    // passed by user
    autonomous?: boolean
}

properties which have an asterisk * mean that they're optional

Routes

Routes are what routes are. Set a method, a url, and a response handler. Each response handler has context about the application (check interfaces or src/server.ts for examples). Also supports faker.js as generator of fake data.

State

An important part of writing a responsive mock server is state management. A total of three state handlers are provided by the application.

StateHandler

import { StateHandler } from "./state/StateHandler"

const { get: getSimpleState, set: setSimpleState } = StateHandler<string>("default_value")
  • the data is kept in memory, not on database.
  • fastest of the three options.
  • strong support for custom data types.

PersistentStateHandler

import { PersistentStateHandler } from "./state/PersistentStateHandler"

const { get: getPersistentState, set: setPersistentState } = await PersistentStateHandler("default_value")
  • the data kept in memory as well as database.
  • slower than StateHandler, but persists the data in the database.
  • get and set are twin functions, which operate on the same data source.

Orphan

import { RetrieveOrphan, SaveAsOrphan } from "./state/Orphan"

await SaveAsOrphan(key, value)
const data = await RetrieveOrphan(key)
  • the data is kept in database only.
  • slower than others.
  • main advantage : get and set are completely independent functions, useful when you want to define the object maps across different files or love a clean architecture.

Sample File

const { get: getSimpleState, set: setSimpleState } = StateHandler<string>("default_value")
const { get: getPersistentState, set: setPersistentState } = await PersistentStateHandler("default_value")

const triggerMaps: Array<IMayaTriggerDefinition> = [
    {
        name: "TRIGGER_BEFORE_1",
        method: METHOD.GET,
        url: "https://webhook.site/b0ae265d-839f-45fa-9774-c2d8bed11ddb",
        response: async () => {
            console.log("TRIGGER_BEFORE")
        }
    },
    {
        name: "TRIGGER_BEFORE_2",
        method: METHOD.POST,
        url: "https://webhook.site/b0ae265d-839f-45fa-9774-c2d8bed11ddb",
        response: async () => {
            console.log("TRIGGER_BEFORE")
        },
        body: {
            "name": "TRIGGER_BEFORE_2"
        }
    },
    {
        name: "TRIGGER_AFTER_1",
        method: METHOD.GET,
        url: "https://webhook.site/b0ae265d-839f-45fa-9774-c2d8bed11ddb",
        response: async () => {
            console.log("TRIGGER_AFTER")
        }
    },
    {
        name: "TRIGGER_AFTER_2",
        method: METHOD.POST,
        url: "https://webhook.site/b0ae265d-839f-45fa-9774-c2d8bed11ddb",
        response: async () => {
            console.log("TRIGGER_AFTER")
        },
        body: {
            "name": "TRIGGER_AFTER_2"
        }
    },

]

const routeMaps: Array<IMayaRouteDefinition> = [
    {
        method: METHOD.GET,
        url: "/faker/:times",
        response: ({ faker, request: { params } }) => {
            const number = parseInt(params.times)
            const generatorFunction = () => ({
                name: faker.name.findName(),
                organization: faker.company.companyName(),
                dateJoined: faker.date.past(10),
                image: faker.image.people()
            })
            const data = repeat(generatorFunction, number)
            return data
        },
        before: ["TRIGGER_BEFORE_1", "TRIGGER_BEFORE_2"],
        after: ["TRIGGER_AFTER_1", "TRIGGER_AFTER_2"]
    },
    {
        method: METHOD.GET,
        url: "/state-handler",
        response: async () => {
            const data = getSimpleState()
            return { payload: data }
        }
    },
    {
        method: METHOD.POST,
        url: "/state-handler",
        response: async ({ request }) => {
            const value = request.body.value
            setSimpleState(value)
            return { payload: value }
        }
    },
    {
        method: METHOD.GET,
        url: "/persistent-state-handler",
        response: async () => {
            const data = await getPersistentState()
            return { payload: data }
        }
    },
    {
        method: METHOD.POST,
        url: "/persistent-state-handler",
        response: async ({ request }) => {
            const value = request.body.value
            await setPersistentState(value)
            return { payload: value }
        }
    },
    {
        method: METHOD.GET,
        url: "/orphan-state-handler/:key",
        response: async ({ request }) => {
            const key = request.params.key
            const data = await RetrieveOrphan(key)
            return { payload: data }
        }
    },
    {
        method: METHOD.POST,
        url: "/orphan-state-handler/:key",
        response: async ({ request }) => {
            const key = request.params.key
            const value = request.body.value
            await SaveAsOrphan(key, value)
            return { payload: value }
        }
    }
]

Testing

It is recommended to use a service like webhook.site to inspect the requests.

You might also like...

NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE.

NiseLine NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE. Getting Started Launch NiseLine server. docker ru

Jan 24, 2022

NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE.

NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE.

NiseLine NiseLine is inspired by LocalStack. Goal of this tool is to create a mock service for LINE. Getting Started Launch NiseLine server by Docker

Jul 29, 2022

A private chatroom for discussing secret stuff.

A private chatroom for discussing secret stuff.

💬 Socket.IO IRC A private chatroom for discussing secret stuff. The Problem Almost all chatapps nowadays aren't safe enough for private communication

Aug 16, 2022

LIFF Mock is a LIFF Plugin that make testing your LIFF app easy.

LIFF Mock LIFF Mock is a LIFF Plugin that make testing your LIFF app easy. ※ LIFF Plugin feature is available since LIFF SDK v2.19.0. Usage NPM $ npm

Dec 2, 2022

Some stuff for testing, such as mocks, object mother, etc.

Some stuff for testing, such as mocks, object mother, etc.

Built with ❤︎ by maintainers Testing Some stuff for testing, such as mocks, object mother, etc. Installation yarn add git+https://github.com/turnly/te

Jul 21, 2022

A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui

A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui

Welcome to FullStack Next.js template 👋 A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui ✨ Demo Tech Ne

Oct 16, 2022

Test utility to mock `window.matchMedia` for JSDOM environments.

mock-match-media Test utility for mocking window.matchMedia in JSDOM environments. JSDOM doesn't provide support for window.matchMedia, which means te

Oct 12, 2022

This project is a web application that enables users to add, edit and remove tasks they intend to perform. Built with JavaScript, HTML, and CSS.

TO DO List Unit testing using jest Create the to-do List project with webpack. Ultimately, the user should be able to add an item and delete the item

Jul 26, 2022

This is a web application that enables users to add, edit and remove tasks they intend to perform. Built with JavaScript, HTML, and CSS.

TODO LIST It list everything that you have to do, with the most important tasks at the top of the list, and the least important tasks at the bottom. B

Sep 16, 2022
Owner
null
A social network app cloned from Instagram built with Next.Js, Socket.IO and a lots of other new stuff.

Instagram Noob ⚡ A social network app cloned from Instagram built with Next.Js, Socket.IO and a lots of other new stuff. Live Demo: https://instagram-

Hung Minh 20 Oct 19, 2022
Smooth scrolling effect (while using mouse wheel). No jQuery or other unnecessary stuff needed.

scrooth Smooth scrolling effect (while using mouse wheel). No jQuery or other unnecessary stuff needed. Why? I needed that, and I was unable to find p

Rafał Spiżewski 20 Aug 29, 2022
A fast and powerful http toolkit that take a list of domains to find active domains and other information such as status-code, title, response-time , server, content-type and many other

HTTPFY curently in beta so you may see problems. Please open a Issue on GitHub and report them! A Incredible fast and Powerful HTTP toolkit Report Bug

DevXprite 44 Dec 22, 2022
Quickly create an interactive HTML mock-up by auto sourcing lorem ipsum/images generators, with minimal html markup, and no server side code

RoughDraft.js v0.1.5 Quickly mockup / prototype HTML pages with auto-generated content, without additional JavaScript or server side code. <section>

Nick Dreckshage 464 Dec 21, 2022
Skip the ads on Thingiverse, and get straight to the good stuff.

Thingiverse STL Downloader Those ads sure are annoying. Skip 'em, and get straight to the good stuff. This repository is here for the normal purposes

Stephan Casas 17 Mar 13, 2022
A social-media mock app for the ones who love to read - and maybe show it off

?? ?? Cachalote ?? ?? Share what you are reading and find people who also likes it - or not! What does it do? This app focuses on three main questions

Thaís França 3 May 22, 2022
The Remix Stack for deploying to Vercel with testing, linting, formatting, structure and mock for 3rd party API integration.

Remix DnB Stack See it live: https://dnb-stack.vercel.app/ Learn more about Remix Stacks. npx create-remix --template robipop22/dnb-stack What's in th

Robert Pop 61 Dec 13, 2022
A mock Twitter page implemented without, partially with, and then with a design system.

Design Systems Workshop A mock Twitter page implemented without, partially with, and then with a design system. Setup Install npm dependencies, then s

Josh Goldberg 5 Dec 8, 2022
Base-mock-api - Repo to storage my fake api's to use in my 2022 projects.

Base Mock API's Project made 100% with JavaScript, with the objective of creating endpoints to use in projects. Prerequisites Before you begin, ensure

Arthur Cabral 0 Nov 20, 2022
Linely is inspired by LocalStack. Goal of this tool is to create a mock service for LINE.

Linely Linely is inspired by LocalStack. Goal of this tool is to create a mock service for LINE. Setup Docker docker run -d -p 3000:3000 dyoshikawa/li

null 4 Jan 24, 2022