@pact-foundation/pact
Version:
Pact for all things Javascript
234 lines • 8.91 kB
JavaScript
"use strict";
/**
* @module Message
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageConsumerPact = void 0;
exports.synchronousBodyHandler = synchronousBodyHandler;
exports.asynchronousBodyHandler = asynchronousBodyHandler;
const pact_core_1 = __importStar(require("@pact-foundation/pact-core"));
const lodash_1 = require("lodash");
const ramda_1 = require("ramda");
const package_json_1 = require("../package.json");
const logger_1 = __importStar(require("./common/logger"));
const spec_1 = require("./common/spec");
const configurationError_1 = __importDefault(require("./errors/configurationError"));
const v3_1 = require("./v3");
const DEFAULT_PACT_DIR = './pacts';
var ContentType;
(function (ContentType) {
ContentType[ContentType["JSON"] = 0] = "JSON";
ContentType[ContentType["BINARY"] = 1] = "BINARY";
ContentType[ContentType["STRING"] = 2] = "STRING";
})(ContentType || (ContentType = {}));
/**
* A Message Consumer is analogous to a Provider in the HTTP Interaction model.
* It is the receiver of an interaction, and needs to be able to handle whatever
* request was provided.
*/
class MessageConsumerPact {
config;
state = {};
pact;
message;
constructor(config) {
this.config = config;
this.pact = (0, pact_core_1.makeConsumerAsyncMessagePact)(config.consumer, config.provider, (0, spec_1.numberToSpec)(config.spec, v3_1.SpecificationVersion.SPECIFICATION_VERSION_V3), config.logLevel);
this.pact.addMetadata('pact-js', 'version', package_json_1.version);
this.message = this.pact.newMessage('');
if (!(0, lodash_1.isEmpty)(config.logLevel)) {
(0, logger_1.setLogLevel)(config.logLevel);
pact_core_1.default.logLevel(config.logLevel);
}
}
/**
* Gives a state the provider should be in for this Message.
*
* @param {string} state - The state of the provider.
* @returns {Message} MessageConsumer
*/
given(state) {
if (typeof state === 'string') {
this.message.given(state);
}
else {
this.message.givenWithParams(state.name, JSON.stringify(state.params));
}
return this;
}
/**
* A free style description of the Message.
*
* @param {string} description - A description of the Message to be received
* @returns {Message} MessageConsumer
*/
expectsToReceive(description) {
if ((0, lodash_1.isEmpty)(description)) {
throw new configurationError_1.default('You must provide a description for the Message.');
}
this.message.expectsToReceive(description);
return this;
}
/**
* The JSON object to be received by the message consumer.
*
* May be a JSON object or JSON primitive. The contents must be able to be properly
* strigified and parse (i.e. via JSON.stringify and JSON.parse).
*
* @param {string} content - A description of the Message to be received
* @returns {Message} MessageConsumer
*/
withContent(content) {
if ((0, lodash_1.isEmpty)(content)) {
throw new configurationError_1.default('You must provide a valid JSON document or primitive for the Message.');
}
this.message.withContents(JSON.stringify(content), 'application/json');
this.state.contentType = ContentType.JSON;
return this;
}
/**
* The text content to be received by the message consumer.
*
* May be any text
*
* @param {string} content - A description of the Message to be received
* @returns {Message} MessageConsumer
*/
withTextContent(content, contentType) {
this.message.withContents(content, contentType);
this.state.contentType = ContentType.STRING;
return this;
}
/**
* The binary content to be received by the message consumer.
*
* Content will be stored in base64 in the resulting pact file.
*
* @param {Buffer} content - A buffer containing the binary content
* @param {String} contenttype - The mime type of the content to expect
* @returns {Message} MessageConsumer
*/
withBinaryContent(content, contentType) {
this.message.withBinaryContents(content, contentType);
this.state.contentType = ContentType.BINARY;
return this;
}
/**
* Message metadata.
*
* @param {string} metadata -
* @returns {Message} MessageConsumer
*/
withMetadata(metadata) {
if ((0, lodash_1.isEmpty)(metadata)) {
throw new configurationError_1.default('You must provide valid metadata for the Message, or none at all');
}
(0, ramda_1.forEachObjIndexed)((v, k) => {
this.message.withMetadata(`${k}`, JSON.stringify(v));
}, metadata);
return this;
}
/**
* Creates a new Pact _message_ interaction to build a testable interaction.
*
* @param handler A message handler, that must be able to consume the given Message
* @returns {Promise}
*/
verify(handler) {
logger_1.default.info('Verifying message');
return handler(this.reifiedContent())
.then(() => {
this.pact.writePactFile(this.config.dir ?? DEFAULT_PACT_DIR, this.config.pactfileWriteMode !== 'overwrite');
})
.finally(() => {
this.message = this.pact.newMessage('');
this.state = {};
});
}
reifiedContent() {
const raw = this.message.reifyMessage();
logger_1.default.debug(`reified message raw: raw`);
const reified = JSON.parse(raw);
if (this.state.contentType === ContentType.BINARY) {
reified.contents = Buffer.from(reified.contents, 'base64');
}
logger_1.default.debug(`rehydrated message body into correct type: ${reified.contents}`);
return reified;
}
/**
* Returns the Message object created.
*
* @returns {Message}
*/
json() {
return this.state;
}
}
exports.MessageConsumerPact = MessageConsumerPact;
// TODO: create more basic adapters for API handlers
// bodyHandler takes a synchronous function and returns
// a wrapped function that accepts a Message and returns a Promise.
//
// The body type defaults to `AnyJson | Buffer` (the runtime type of
// `m.contents`), but callers may narrow it to a custom shape (e.g. an
// interface describing the JSON they expect to receive) by supplying the
// `B` type parameter. The narrowing is a TypeScript-only assertion; the
// runtime value is still whatever the producer sent.
function synchronousBodyHandler(handler) {
return (m) => {
const body = m.contents;
return new Promise((resolve, reject) => {
try {
const res = handler(body);
resolve(res);
}
catch (e) {
reject(e);
}
});
};
}
// bodyHandler takes an asynchronous (promisified) function and returns
// a wrapped function that accepts a Message and returns a Promise.
// See `synchronousBodyHandler` for the rationale behind the `B` parameter.
// TODO: move this into its own package and re-export?
function asynchronousBodyHandler(handler) {
return (m) => handler(m.contents);
}
//# sourceMappingURL=messageConsumerPact.js.map