Counterfact

OpenAPI to TypeScript generator and mock server

This project is maintained by pmcelhaney

Counterfact is the mock server that front end engineers need to be productive

Quick Start | Documentation | Contributing


Coverage Status Mutation testing badge MIT License

Features

Use Cases

Unlike similar tools, Counterfact is not limited to canned or randomly generated responses. It can mimic as much or as little of the business logic in your n-tier / cloud-native back end as you want. Test end-to-end scenarios in your front end code as if a lighting-fast implementation of the real backend is running on your machine. Because it is.

As a front end dev, when you have complete and granular control over the back end, and you can modify anything on a whim, it enhances your developer experience in ways that are hard to describe.

What does the code look like?

GET /hello/world
// ./paths/hello/world.js
export const GET = () => "Hello World!";
Using the Swagger Petstore as an example, here’s one way to implement GET /pet/{petId}` and POST `POST /pets`.
// ./paths/pet/{petId}.js
export const GET = ({ context, response, path }) => {
  const pet = context.getPetById(path.petId);

  if (!pet) {
    return response[404].text(`Pet with ID ${path.petID} not found.`);
  }

  return response[200].json(pet);
};
// ./paths/pets.js
export const POST = ({ context, response, body }) => {
  const pet = context.addPet(body);

  return response[200].json(pet);
};

// ./paths/$.context.ts
class PetStore () {
    pets = {};

    getPetById(petId) {
        return pets[id];
    }

    addPet(pet) {
        this.pets[pet.id] = pet;
    }
}

export default new PetStore();

If you have a Swagger / OpenAPI spec, you'll be up and running in seconds

For example, run the following command to generate code for the Swagger Petstore.

npx counterfact@latest https://petstore3.swagger.io/api/v3/openapi.json api --open

That command generates and starts a TypeScript implementation of the Swagger Petstore which returns random, valid responses. Not too shabby for a few seconds of work!

It's your server. Do whatever you want with it.

Edit the code under ./api/paths to implement real behavior, as we did in the JavaScript examples above. Store and retrieve data, perform calculations, filter / sort / paginate, whatever it takes the make the API real enough to support the development and testing of your front end.

See the Usage Guide for details.


Counterfact is brand new as of November 30, 2022. Please send feedback / questions to pmcelhaney@gmail.com or create a new issue. If you like what you see, please give this project a star!