OpenAPI to TypeScript generator and mock server
This project is maintained by pmcelhaney
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.
GET /hello/world
// ./paths/hello/world.js
export const GET = () => "Hello World!";
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();
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!
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.
$.query.
" to list all of the available parameters.context.addPet({id: 2, name: "Fido"})
to add a pet to the store. Then view the pet you just added at http://localhost:3100/pet/2
.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!