6. Write the API consumer
The Consumer
Time to create our consumer code base. For the sake of simplicity, we're going to focus only on the bits of our application that communicate to the provider. In our project, they are:
The model (the
Product
class), representing the data returned from the Product API:example-bi-directional-consumer-mountebank/src/api.js
The API client (the
ProductApiClient
) which will be responsible for making the HTTP calls to the Product API and returning an internal representation of an Product:example-bi-directional-consumer-mountebank/src/product.js
Install the dependencies for the project: npm i
Product Model
src/product.js
export class Product { constructor({id, name, type}) { if (!id || !name || !type) { throw Error("id, name and type are required properties") } this.id = id this.name = name this.type = type } }
Product API Client
Here is a version of our API client code. This code is responsible for fetching products from the API, and returning a Product
:
src/api.js
const axios = require("axios"); const adapter = require("axios/lib/adapters/http"); const { Product } = require("./product"); axios.defaults.adapter = adapter; export class ProductAPIClient { constructor(url) { if (url === undefined || url === "") { url = process.env.BASE_URL; } if (url.endsWith("/")) { url = url.substr(0, url.length - 1); } this.url = url; } withPath(path) { if (!path.startsWith("/")) { path = "/" + path; } return `${this.url}${path}`; } async getAllProducts() { return axios .get(this.withPath("/products")) .then((r) => r.data.map((p) => new Product(p))); } async getProduct(id) { return axios .get(this.withPath("/product/" + id)) .then((r) => new Product(r.data)); } }
This class, and specifically the getProduct()
and getAllProducts
methods, will be the target of our contract tests.
You can pick your consumer now:
Fork and clone the consumer
Fork the example-bi-directional-consumer-mountebank project in to your own Github account (click the 'Fork' button in the top right).
Clone the repositories on to your local machine.
git clone git@github.com:<YOUR_GITHUB_USERNAME>/example-bi-directional-consumer-mountebank.git
Install the dependencies.
npm install
Check
Before moving to the next step, check the following:
You are in the correct directory
cd /root/example-bi-directional-consumer-mountebank
You have run
npm i
and the dependencies have been installedYou have studied and understood the Product class:
example-bi-directional-consumer-mountebank/src/product.js
You have studied and understood the API client:
example-bi-directional-consumer-mountebank/src/api.js