@case-contract-testing/case
Version:
Next-generation contract testing suite
109 lines (108 loc) • 6.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeBrokerApi = void 0;
// We need to allow underscores because they're part of the HAL response
/* eslint-disable no-underscore-dangle */
const entities_1 = require("../../entities");
const axios_1 = require("./axios");
const caseVersion_1 = require("../../entities/caseVersion");
const trimSlash = (str) => {
if (str.endsWith('/')) {
return trimSlash(str.substring(0, str.length - 1));
}
return str;
};
const makeBrokerApi = (configContext) => {
const authToken = configContext['case:currentRun:context:brokerCiAccessToken'];
const baseUrl = configContext['case:currentRun:context:brokerBaseUrl'];
const basicAuth = configContext['case:currentRun:context:brokerBasicAuth'];
if (baseUrl === undefined || baseUrl === '') {
throw new entities_1.CaseConfigurationError("Can't access a broker without specifying the base URL. Set the environment variable CASE_BROKER_BASEURL or the config property brokerBaseUrl");
}
if (typeof baseUrl !== 'string') {
throw new entities_1.CaseConfigurationError(`Expected the baseurl to be a string, but it was '${typeof authToken}'`);
}
if (authToken === undefined && basicAuth === undefined) {
throw new entities_1.CaseConfigurationError("Can't access a broker without an authorization token or basic auth set. Set the environment variable CASE_BROKER_CI_TOKEN");
}
if (authToken !== undefined) {
if (authToken === '') {
throw new entities_1.CaseConfigurationError("Can't access a broker without an authorization token. Set the environment variable CASE_BROKER_CI_TOKEN");
}
if (typeof authToken !== 'string') {
throw new entities_1.CaseConfigurationError(`Expected the authToken to be a string, but it was '${typeof authToken}'`);
}
}
if (authToken === undefined && basicAuth === undefined) {
throw new entities_1.CaseConfigurationError("Can't access a broker without an authorization token or basic auth set. Set the environment variable CASE_BROKER_CI_TOKEN");
}
const auth = (authToken ?? basicAuth);
const server = (0, axios_1.makeAxiosConnector)(trimSlash(baseUrl), auth);
return {
publishContract: (contract, version, logContext) => {
// TODO: Make this a first class object
logContext.logger.debug(`Publishing contract for ${contract.description.consumerName}@${version} -> ${contract.description.providerName} to broker at ${baseUrl}`);
const path = `/pacts/provider/${encodeURIComponent(contract.description.providerName)}/consumer/${encodeURIComponent(contract.description.consumerName)}/version/${encodeURIComponent(version)}`;
logContext.logger.maintainerDebug(`Publish path is: ${path}`);
return server.authedPut(path, contract, logContext).then((d) => {
logContext.logger.debug(`Published successfully`);
logContext.logger.deepMaintainerDebug(`Published result was`, JSON.stringify(d));
});
},
publishContractAdvanced: (contract, version, branch, logContext) => {
logContext.logger.debug(`Publishing contract for ${contract.description.consumerName}@${version} -> ${contract.description.providerName} to broker at ${baseUrl}`);
return server.authedPost('/contracts/publish', {
pacticipantName: contract.description.consumerName,
pacticipantVersionNumber: version,
...(branch !== false ? { branch } : {}),
tags: [],
contracts: [
{
consumerName: contract.description.consumerName,
providerName: contract.description.providerName,
specification: 'pact',
contentType: 'application/json',
content: Buffer.from(JSON.stringify(contract)).toString('base64'),
},
],
}, logContext);
},
publishVerificationResults: (contract, success, providerVersion, branch, logContext) => (0, axios_1.makeAxiosConnector)(contract._links['pb:publish-verification-results'].href, auth)
.authedPost('', {
providerApplicationVersion: providerVersion,
success,
...(branch !== false ? { branch } : {}),
verifiedByImplementation: 'ContractCase',
verifiedByVersion: caseVersion_1.caseVersion,
executionDate: new Date(Date.now()).toISOString(),
tags: [],
}, logContext)
.then((t) => t),
downloadContract: (url) => (0, axios_1.makeAxiosConnector)(url, auth).authedGet(),
urlsForVerification: (serviceName, logContext) => {
logContext.logger.debug(`Finding contracts to verify for service '${serviceName}' on broker at ${baseUrl}`);
const path = `/pacts/provider/${encodeURIComponent(serviceName)}/for-verification`;
logContext.logger.maintainerDebug(`forVerification path is: ${path}`);
return server
.authedPost(path, {
consumerVersionSelectors: [
{
mainBranch: true,
},
{
deployedOrReleased: true,
},
{ latest: true },
],
providerVersionTags: ['main'],
}, logContext)
.then((d) => {
logContext.logger.deepMaintainerDebug(`Pacts for verification responded with`, JSON.stringify(d, undefined, 2));
const numPacts = d._embedded.pacts.length;
logContext.logger.debug(`Broker returned ${numPacts} URLs to possible contracts for verification`);
return d._embedded.pacts.map((contract) => contract._links.self);
});
},
};
};
exports.makeBrokerApi = makeBrokerApi;