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

@bbc/consumer-contracts

v4.4.2

Published

Consumer driven contracts for Node.js

Downloads

762

Maintainers

lores-bbclores-bbcemma-moodieemma-moodiegoswat01goswat01zahidz01zahidz01ashrau01ashrau01lokesh_srinivasalokesh_srinivasaandrewc0617andrewc0617kierankellyspyrosoftkierankellyspyrosoftgozcue01-bbcgozcue01-bbccodedbypaulcodedbypauldas-partnerdas-partnerrodger-threlfallrodger-threlfallcatherine_hprcatherine_hprkarim-sprkarim-sprsekhar01sekhar01naivinh.ta.bbcnaivinh.ta.bbctalal-adnantalal-adnangrace_alagaratnamgrace_alagaratnamfergusreidbbcfergusreidbbcpallavisharmabbcpallavisharmabbcgingertonicstgingertonicstmichaelmrnmichaelmrnbhartn01bhartn01rtholmes96rtholmes96liamcannnliamcannnbbcjlbbcjlchris.andrews05chris.andrews05mint-dewitmint-dewitamitch07amitch07tom-cowardtom-cowardhconway24hconway24kelvininukbbckelvininukbbcphillbbcphillbbcdale-waterworthdale-waterworthlbird96lbird96lauramihai-bbclauramihai-bbcsinghn08singhn08reeda06reeda06vlee.bbcvlee.bbchannah-slaterhannah-slaterlukeparker02lukeparker02notten13notten13foxk13foxk13archibaldersonarchibaldersonjfsbbcjfsbbcshrey-glashrey-glaszpytfire-bbcszpytfire-bbcalexa_salexa_sbridga03bridga03pjlangleypjlangleypererr03pererr03glorhie99glorhie99roopashree-ramachandraiahroopashree-ramachandraiahjibberjimbbcjibberjimbbcjemmapjemmapvinodranevinodraneteyahbdteyahbdshahp07shahp07cameronsabudabbccameronsabudabbcmattwright-bbcmattwright-bbcjmegmanjmegmanmomahboobianmomahboobianchrisjmuddchrisjmuddbrooklyn-bbcbrooklyn-bbcdavidkopcokdavidkopcokrosie.inmanrosie.inmanbrianbayesbrianbayespeterrichmondbbcpeterrichmondbbcduncan-corps-bbcduncan-corps-bbcchaitanyajjchaitanyajjjadhav02jadhav02bensegnibbcbensegnibbcsmithd24smithd24elliottnewtonbbcelliottnewtonbbcanthonyporthouseanthonyporthousegiacomobggiacomobgtiposupporttiposupportmichellebbcmichellebbcashwinrdnashwinrdnglennalcockglennalcockmianhassanimianhassanirbtwrbtwishaaqiqbalishaaqiqbalmerhaymerhayosada.paranaliyanageosada.paranaliyanageshawnhardernhipposhawnhardernhippoeobreobrsofiadionisiosofiadionisiodavid.toluhidavid.toluhichriss901chriss901pshaw03pshaw03lokh01lokh01nirerr01nirerr01nendhruvnendhruvrichard_gilpinrichard_gilpinpaulybpaulybed.guccioneed.guccionemessage-keepermessage-keeperfelicityrcfelicityrccraigatcraigatkatharinaschulzkatharinaschulzfuzzyjessfuzzyjessrlfbbcrlfbbcken.barnettken.barnettcolinr2colinr2darkoa01darkoa01anthonygoodchildanthonygoodchildbbc-cicdguild-machineuserbbc-cicdguild-machineuserrlam0rlam0hine24hine24milkywaynian-bbcmilkywaynian-bbcmathieuloutremathieuloutredavidsolsonapuertasdavidsolsonapuertassunnybbcsunnybbcwssystems-integrationwssystems-integrationajrobzajrobzanatdeanbeebanatdeanbeebtzaman76tzaman76tomwieck2tomwieck2jamese00jamese00fahad-s75fahad-s75tdoukinitsastdoukinitsasghazif03ghazif03mesenmesenndbbcndbbcyonglexuyonglexusan-raisan-rainenehbnenehbchrisorrickbbcchrisorrickbbcbrotherkaifbrotherkaiflaitangbbclaitangbbcakumac01akumac01ktalagaktalagabbc-sounds-offproductbbc-sounds-offproductabrarkayabrarkaywillsidlebbcwillsidlebbcy.milliony.millioncraigjwrightcraigjwrightbevand10bevand10sbeck1sbeck1ridwan_devridwan_devabdu01abdu01vidhya09vidhya09kirbyc02kirbyc02carlaslatterycarlaslatterylcheffernanlcheffernanalexshelleyalexshelleysadia-taznimsadia-taznimrichag04richag04dannymeloydannymeloyjpark0224jpark0224michaelmccoymichaelmccoyabz.meabz.mekasunmadushankakasunmadushankakieranjoycekieranjoycejamesscarboroughjamesscarboroughfrankj05frankj05dannydaviesbbcdannydaviesbbcjcablejcablestephenlovellstephenlovellsgoudhamsgoudhamnathjoycenathjoyceespirn01espirn01glenndavidsonbbcglenndavidsonbbcjamesdesqjamesdesqhelen_morrishelen_morriscdorrian871cdorrian871olssod02olssod02imran.haidryimran.haidryjonathan-gillespiejonathan-gillespieazineh2023azineh2023aliciagrandjeanaliciagrandjeanbbc-tv-open-sourcebbc-tv-open-sourcelaura01laura01rosemcnallyrosemcnallyiulia.bukhvalovaiulia.bukhvalovahjerlinghjerlingfelixmercermossfelixmercermossmatt-harris-bbcmatt-harris-bbcpeterc89peterc89tsadlerbbctsadlerbbcaabbabaraabbabarkatyasakatyasacallap03callap03chris.darlastonchris.darlastonwhitew02whitew02tcsquaredtcsquareddwalker487dwalker487holladholladorforn01orforn01amitsavantamitsavantnorrib01norrib01jakepointingjakepointingllouisetaylorbbcllouisetaylorbbccharlie-cowan-bbccharlie-cowan-bbcrobbmcquistonrobbmcquistonjames.bungayjames.bungaygloandcogloandcoalbertlobbcalbertlobbcwelshl02welshl02fglover84fglover84yoshihirokasaharayoshihirokasaharahafsa-abdulsalimhafsa-abdulsalimabicoeabicoejonyardleyjonyardleyshaquillaevelynshaquillaevelynfalko189falko189fullerlee-bbcfullerlee-bbccheunm01cheunm01clairelittler-bbcclairelittler-bbcrichhildyardrichhildyardigorisolomonigorisolomontomnuttallbbctomnuttallbbcbbcparfaitbbcparfaitgarwod01garwod01inkenhenneinkenhennearnvshukla89arnvshukla89davidayooladavidayooladavid-boydelldavid-boydellmarta.martimarta.martiallena61allena61priyal2024priyal2024caeseribrahimcaeseribrahimtampie85tampie85ben.bagley.bbcben.bagley.bbctamsingreentamsingreenaaronkenyonaaronkenyonmnharrisonmnharrisonmadamotmadamotuk-ummeuk-ummejkordekbbcjkordekbbcdoladdoladsmugpiesmugpieshanthichaitanyashanthichaitanyabiguzc01biguzc01silidsilidtariqatiatariqatiam-mafenim-mafenimarktaylorbbcmarktaylorbbcronanmockettronanmocketthangbbchangbbcryanmcbbcryanmcbbcridwanchoridwanchoglediatorglediatorlantana-alilantana-aliashtuckbbcashtuckbbcj616s-bbcj616s-bbcken0310ken0310mangrjuimangrjuijakub.gjakub.godonnellbbcodonnellbbcnpmbsnpmbsteju_jakkiteju_jakkigavyn_bbcgavyn_bbcyusuf963myusuf963mjoshuacaddyjoshuacaddyamelialloydbbcamelialloydbbcgeorge-brookegeorge-brookemknishmknishj-e-borehamj-e-borehambozziebozzieluke01455luke01455michael_mulgrewmichael_mulgrewjrew-bbcjrew-bbcandyj-bbcandyj-bbctmocotmocoizzy-pickeringizzy-pickeringajitsanto09ajitsanto09bad-horse-bbcbad-horse-bbcolivia-p-mooreolivia-p-moorejsheriffbbcjsheriffbbcsubhathirarengarajsubhathirarengarajshez-bbcshez-bbcryanwaudbyryanwaudbyamritbbcamritbbcriver-bbcriver-bbcm-al-maarym-al-maaryguptaa01guptaa01allybeeballybeebjpeutherer1jpeutherer1sframptonsframptonsuzanna_kwongsuzanna_kwongallbuttergallbuttergkatie.frostkatie.frostjackhoggbbcjackhoggbbcvaughr03vaughr03graham-armstrong-bbcgraham-armstrong-bbcrussellbroughtonrussellbroughtontomchamberlainuktomchamberlainukmathkeehanmathkeehandio-pdio-panderb08anderb08cattranfieldcattranfieldabd.el-aziz.extabd.el-aziz.extdaniel.ochieng.extdaniel.ochieng.extmaxwec01maxwec01bbc_ivanalvarezbbc_ivanalvarezdeepaakhildeepaakhilsimm90simm90award2022award2022iuketayloriuketaylormatthewtaylorworkmatthewtaylorworkjamiebower185jamiebower185alexchestersbbcalexchestersbbcshoba15shoba15lazzaa01lazzaa01benjwheelerbenjwheelerlexedwardsbbclexedwardsbbcgeoffbbcgeoffbbcyavor-atanasovyavor-atanasovs-zaid-ss-zaid-sbradleyphippsbradleyphippszaintahirbbczaintahirbbcroberp05roberp05garydaviesgarydaviescarrejoe3carrejoe3dataforce-jenkinsdataforce-jenkinscobair01cobair01gavinwright292gavinwright292andysteadbbcandysteadbbcovsichtiovsichtisimonpittsimonpittclaydelasclaydelasdo0g.bbcdo0g.bbcmattbbcmattbbcfeglese_bbcfeglese_bbcandywebb2-bbcandywebb2-bbccjewell47cjewell47chibbcchibbckavbis066kavbis066fahad-75fahad-75edembbcedembbcchalikovchalikovsamgjwsamgjwmacgll01macgll01eloiseceloisecurbanm13urbanm13wormab01wormab01nicholasgriffin_bbcnicholasgriffin_bbcwoodp11woodp11sevisariisiksevisariisikdaniel.helendaniel.helenstevensamsstevensamsalistair.gempfalistair.gempfbbc-delivery-engineeringbbc-delivery-engineeringsheilab6sheilab6jonpbbcjonpbbcbennuttallbennuttallkmurphy3377kmurphy3377johnnewmanjohnnewmanchris-s-thompsonchris-s-thompsonryanmckennabbcryanmckennabbcbbc-voice-pipelinebbc-voice-pipelinesimon_taylorsimon_taylordrrobharperdrrobharperjodiw_bbcjodiw_bbchowelr03howelr03peteslomanpeteslomanjohnsn27johnsn27olivierhuinbbcolivierhuinbbcparticipation-jenkinsparticipation-jenkinsbillt-bbcbillt-bbcayu-idjajaayu-idjajasgospodinovsgospodinovcharliercharliertonymcbethtonymcbethmagdalena.glancmagdalena.glancrichardfeltonrichardfeltonjezbur-bbcjezbur-bbcchalfordchalfordrobfarrrobfarrsilver-jenkinssilver-jenkinsliam.jenkinsonliam.jenkinsonrisheet_thanki_bbcrisheet_thanki_bbcmartmarmamartmarmatimasplintimasplinmdtbuildmdtbuildcps-supportcps-supportbelloro_bbcbelloro_bbcbbcdjbbcdjwillcottwillcottstephegn_bbcstephegn_bbcbbc-web-corebbc-web-corebbc-adminbbc-adminiplayer-web-jenkinsiplayer-web-jenkinsarunbhari11arunbhari11lokih_lokih_cathawkercathawkerpatelj03patelj03padmavathi.tatavartypadmavathi.tatavartyramkup01ramkup01aggari01aggari01matthewcardmatthewcardtomhobbsbbctomhobbsbbcsmiths124smiths124daniel-baileydaniel-baileyandycharrisandycharrissamcausersamcauserclarkb12clarkb12jack_mcpolandjack_mcpolandwilldahlgreenwilldahlgreenthomsonpthomsonpbbcbsdbbcbsdonlyonehasonlyonehasbbc-cloudengbbc-cloudengmcmanj04mcmanj04rthompson1991rthompson1991neha0508neha0508sbasonsbasonjezhodgesbbcjezhodgesbbclewerlewersteven-bbcsteven-bbcbbc-news-jenkinsbbc-news-jenkinsbenjaa14benjaa14craigjcraigjtarqwyntarqwynchrisn-bbcchrisn-bbcnjh-bbcnjh-bbcsimongregorysimongregorymarkturnermarkturnerpetra-atpetra-atiplayerradio-awsiplayerradio-awsmonsaimonsaisubsidelsubsidelbbcrdbbcrddanmdanmrbryerrbryerjamesreedjamesreedwyellwyelljim-johnson-rollingsjim-johnson-rollingsstephenrobertsbbcstephenrobertsbbcskillc01skillc01dan.thomsonbbcdan.thomsonbbcpcs-amp-jenkinspcs-amp-jenkinsmark.irelandmark.irelandmedia-playout-jenkinsmedia-playout-jenkinschrisowenchrisowenbbc-cd-jenkinsbbc-cd-jenkinslangtonmlangtonmpartner-platform-jenkinspartner-platform-jenkinsapi-management-jenkinsapi-management-jenkinsweather-jenkinsweather-jenkinsbbc-isitebbc-isiteadamxaadamxamatt-rhys-jones-bbcmatt-rhys-jones-bbcscottjarvisscottjarvismarcburrowsmarcburrowschrismarsdenchrismarsdenneilcraigneilcraigeagerterrier_bbceagerterrier_bbcawalsh90awalsh90anthonygreenanthonygreengel-jenkinsgel-jenkinsmiket_bbcmiket_bbcdarrenlucas.bbcdarrenlucas.bbcrozgonyiovarozgonyiovaiblibljana345jana345jlsorakjlsorakabigaelabigaeltom-wrtom-wrraulfuentesraulfuentesdaramaguiredaramaguiremark.howittmark.howitteamonnsullivaneamonnsullivansamirichardsonsamirichardsonhenrywarnehenrywarneshumphreyshumphreyhannahdaddhannahdaddbeckytravbeckytravkerrynscrivenkerrynscrivensport-web-jenkinssport-web-jenkinskcoyle-bbckcoyle-bbcadama03adama03daniel.ellisdaniel.ellisbbcconnectionsbbcconnectionsiain-bbciain-bbcwilsoh58wilsoh58timhewitttimhewittbrittvarnombrittvarnomashcleaveashcleavelydiamoolydiamooyoudyyoudyben_newcombeben_newcombeoliviadruryoliviadrurybbc-gnl-cibbc-gnl-cibbc-morphbbc-morphseancarrollseancarrolldavidbuckhurstdavidbuckhurstitv-ci-machineitv-ci-machineaudienceplatformdevaudienceplatformdevbbc-archivesearch-development-teambbc-archivesearch-development-teamjonathanballsjonathanballssounds-web-jenkinssounds-web-jenkinsobriet04obriet04mikeybykermikeybykerbbc-onlinebbc-onlinecisnkycisnkydustin-bbcdustin-bbcrmsdevrmsdevalasdairstalkeralasdairstalkerjackrmjackrmdwaleesdwaleestomfranciswinningtontomfranciswinningtonthomam67thomam67locator-deploylocator-deployrolandosorbellirolandosorbellijordanholtjordanholtmartysaintymartysaintymassimuramassimurarachael-waddingtonrachael-waddingtongarthcogarthcoandrewscfcandrewscfcchatbnchatbnchriskaychriskaymckayj07mckayj07nickshanksnickshankshextenhextenevebullochevebullochamnpmamnpmlaura94laura94dudardudarcoderkindcoderkindgw8gw8karen_ckaren_cleobsleobsnerosivanerosivalanaceriselanaceriseandywandywfmsupp03fmsupp03fostukfostukleedriscollleedriscollabigailgabigailgnicolabuckhurstnicolabuckhurstacarlson0000acarlson0000education-jenkinseducation-jenkinsallishultesallishulteskeithcrooksbbckeithcrooksbbclawrencep_bbcrdlawrencep_bbcrdleedoughtyleedoughtyandyrobinson01andyrobinson01blundj02blundj02sgrobisonsgrobisonlukedeightonlukedeightonbinhbuibinhbuiinsyn-jenkinsinsyn-jenkinskite-jenkinskite-jenkinsdaniel_brown_bbcdaniel_brown_bbcwaindc01waindc01hanleg03hanleg03bjorn_twachtmannbjorn_twachtmanntasiotasioemupatrolemupatroljonpollardbbcjonpollardbbchellap01hellap01bbc-fatimabbc-fatimaangelinalblythangelinalblythcardl01cardl01decygdecygsalmah95salmah95kamara.bennettkamara.bennettkevin.mackaykevin.mackaypmaudsleypmaudsleyinti0inti0bbcrd-artifactorybbcrd-artifactoryparwiz_sharifiparwiz_sharifigarethjdaviesgarethjdaviesdavidthorpebbcdavidthorpebbcnorrid02norrid02priyapolinenipriyapolinenithomaspreecebbcthomaspreecebbcjason.leemingjason.leemingcaporp01caporp01nanbobnanbobswatitabibswatitabibianarundaleianarundaleshaziashaziabeethechangebeethechangesteve_culverwellsteve_culverwellmattowenukmattowenukaaronmooreaaronmoore56yards56yardssimontannersimontannermilkywaynianmilkywaynianalexjn15alexjn15assizpereiraassizpereiraiplayer-pc-downloads-pipeline-botiplayer-pc-downloads-pipeline-botchrispnicholsonchrispnicholsonbbc-search-and-navigationbbc-search-and-navigationusmanbuildsusmanbuildsstuart_jennings_bbcstuart_jennings_bbcjacobprycejacobprycemattgreenhammattgreenhamcv-bbccv-bbcrobcattrobcattnewslabs-jenkinsnewslabs-jenkinsjoshcoventryjoshcoventrydave.at.bbcdave.at.bbcsarahrainbowsarahrainbowfarahjabrifarahjabridavid.verbenyidavid.verbenyiresist01resist01

Readme

NPM downloads

Consumer-driven contracts in JavaScript

Consumer-driven contracts let you move fast without breaking things.

API consumers codify their expections of your service in an executable contract. This defines the type of response that they expect for a given request. Contracts give you an insight into which parts of your API clients depend on, and which parts can be changed without fear of breaking them.

This project lets you write executable contracts in JavaScript. It uses request to make HTTP requests and Joi to validate API responses. Contracts are defined as JavaScript modules in a contracts directory at the root of your project and can be executed using the consumer-contracts tool.

Getting started

Install the consumer-contracts tool globally:

npm install --global consumer-contracts

Install the consumer-contracts module locally (this gives you access to the contract definition interface in your contract files):

npm install --save-dev consumer-contracts

Create a contracts directory at the root of your project:

mkdir contracts

Create a JavaScript file within the contracts directory for your first contract. The example below is a contract for the GitHub User API, we'll call it user-api.js. In this example, the consumer depends on the login, name and public_repos properties returned in the response body.

var Contract = require("@bbc/consumer-contracts").Contract;
var Joi = require("@bbc/consumer-contracts").Joi;

module.exports = new Contract({
  name: "User API",
  consumer: "My GitHub Service",
  request: {
    method: "GET",
    url: "https://api.github.com/users/robinjmurphy",
  },
  response: {
    status: 200,
    body: Joi.object().keys({
      login: Joi.string(),
      name: Joi.string(),
      public_repos: Joi.number().integer(),
    }),
  },
});

To validate the contract, run the following command at the root of your project directory:

consumer-contracts run

You should see that the contract validates:



  ✓ My GitHub Service – User API


  1 passing

Asynchronous construction of a contract

If you need to perform asynchronous operations to set up a contract then you can instead export a function that returns a Contract:

var Contract = require("@bbc/consumer-contracts").Contract;
var Joi = require("@bbc/consumer-contracts").Joi;

module.exports = async function () {
  const username = await getUsername();
  return new Contract({
    name: "User API",
    consumer: "My GitHub Service",
    request: {
      method: "GET",
      url: `https://api.github.com/users/${username}`,
    },
    response: {
      status: 200,
      body: Joi.object().keys({
        login: Joi.string(),
        name: Joi.string(),
        public_repos: Joi.number().integer(),
      }),
    },
  });
};

Anatomy of a contract

Each contract contains four required properties; consumer, name, request and response.

var Contract = require("@bbc/consumer-contracts").Contract;
var Joi = require("@bbc/consumer-contracts").Joi;

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  request: {
    // ...
  },
  response: {
    // ...
  },
});

consumer

The consumer property appears in the output of the consumer-contracts tool and should be the name of the consuming service that the contract applies to.

name

The name property appears in the output of the consumer-contracts tool and helps you identify each individual contract.

request

The request property defines the HTTP request that the contract applies to. All of the options supported by request are valid. This means you can specify headers and SSL configuration options (among other things) for a given request:

request: {
  method: 'GET',
  url: 'https://exmaple.com/users/fred',
  headers: {
    Accept: 'text/xml'
  },
  pfx: fs.readFileSync('/path/to/my/cert.p12'),
  passphrase: 'my-cert-passphrase'
}

When running under certain environments you may receive SSL errors regarding a CA file. If you know that strict trust checking is not required in this situation you may set strictSSL: false on the above request object, which should resolve the issue.

response

The response object validates the response returned by your service. The entire object is treated as a Joi schema that validates the res object returned by request. This means that the response's status code, headers and JSON body can all be validated using Joi's flexible schema language. The following default options are passed to Joi's validate() function:

{
  allowUnknown: true,
  presence: 'required'
}

This means that any fields you choose to validate are required by default. To indicate that a field is optional, use the optional() modifier.

If you need to override the default Joi options, you can use the optional joiOptions property in your contract.

Validating the response code

To require a specific HTTP status code, set the status property to that value:

response: {
  status: 200;
}

To allow a range of different status codes, you can use Joi's valid() function:

response: {
  status: Joi.any().valid(200, 201, 202);
}

Validating the response headers

The response headers can be validated using a Joi schema:

response: {
  headers: Joi.object().keys({
    Location: Joi.string().regex(/\/users\/\d+/),
    "Content-Type": "application/json",
  });
}

Validating the response body

The response body can be validated using a Joi schema:

response: {
  body: Joi.object().keys({
    name: Joi.string(),
    items: Joi.array().items(
      Joi.object().keys({
        id: Joi.number.integer(),
      }),
    ),
  });
}

client optional

You can use a pre-configured request client for your contracts using the client property. This can be useful when you have a set of common request options across contracts.

var Contract = require("@bbc/consumer-contracts").Contract;
var Joi = require("@bbc/consumer-contracts").Joi;
var client = require("request").defaults({
  headers: {
    authorization: "Bearer xxx",
  },
});

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  request: {
    // ...
  },
  response: {
    // ...
  },
  client: client,
});

before optional

If your contract requires some setup (e.g. populating an API with data) you can use the before property. It takes a function that will be run before the contract executes.

You can either pass a function that receives a callback argument which will be called when setup is complete:

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  before: function (done) {
    // setup
    done();
  },
  request: {
    // ...
  },
  response: {
    // ...
  },
});

Or pass an asynchronous function that will be awaited on:

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  before: async function () {
    // setup
  },
  request: {
    // ...
  },
  response: {
    // ...
  },
});

after optional

If your contract requires some cleanup you can use the after property. It takes a function that will be run after the contract executes.

You can either pass a function that receives a callback argument which will be called when cleanup is complete:

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  request: {
    // ...
  },
  response: {
    // ...
  },
  after: function (done) {
    // cleanup
    done();
  },
});

Or pass an asynchronous function that will be awaited on:

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  request: {
    // ...
  },
  response: {
    // ...
  },
  after: async function () {
    // cleanup
  },
});

joiOptions optional

Overrides the default Joi validation options.

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  request: {
    // ...
  },
  response: {
    // ...
  },
  joiOptions: {
    allowUnknown: false,
  },
});

retries optional

Retries the contract retries times if it fails on the first attempt.

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  request: {
    // ...
  },
  response: {
    // ...
  },
  retries: 2,
});

retryDelay optional

Used with retries to wait retryDelay milliseconds between each retry.

module.exports = new Contract({
  name: "Contract name",
  consumer: "Consumer name",
  request: {
    // ...
  },
  response: {
    // ...
  },
  retries: 2,
  retryDelay: 3000,
});

Specifying multiple contracts

Can be achived by returning an array of contracts.

module.exports = [
  new Contract(),
  // ...
  new Contract(),
  // ...
];

CLI

run

To validate all of the contracts in the contracts directory, type:

consumer-contracts run

This works recursively, which means you can keep the contracts for each of your consumers in a separate subdirectory.

To run a single contract, pass a filename to the run command:

consumer-contracts run ./contracts/consumer-a/contract-1.js

Programmatic Usage

To validate an array of contracts programmatically, first require the validateContracts function:

var validateContracts = require("@bbc/consumer-contracts").validateContracts;

The validateContracts function can then be called with an array of contracts and a callback function which takes two arguments, error and results:

var contracts = [
  new Contract(...),
  new Contract(...)
];

var handleContractValidations = function (err, res) { ... }

validateContracts(contracts, handleContractValidations);

The error argument will always be null, as consumer-contracts will always run every contract in the array rather than failing fast, as such, error handling must deal with the err field of each object in the results array as detailed below.

The results will be an array of objects with fields contract and err. The contract field of the result object contains the executed Contract object including any before and after fields. The err field contains any error that occurred when validating the specific contract. Error handling should check the err field of every result object is null before declaring the contract suite as having been run successfully.