Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/transport/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface TransportFunction {
(message: Message, options?: Options): Promise<unknown>;
}

const emitterDefaults = { binding: HTTP, mode: Mode.BINARY };
/**
* emitterFactory creates and returns an EmitterFunction using the supplied
* TransportFunction. The returned EmitterFunction will invoke the Binding's
Expand All @@ -41,11 +42,11 @@ export interface TransportFunction {
* @param {Mode} options.mode the encoding mode (Mode.BINARY or Mode.STRUCTURED)
* @returns {EmitterFunction} an EmitterFunction to send events with
*/
export function emitterFor(fn: TransportFunction, options = { binding: HTTP, mode: Mode.BINARY }): EmitterFunction {
export function emitterFor(fn: TransportFunction, options = emitterDefaults): EmitterFunction {
if (!fn) {
throw new TypeError("A TransportFunction is required");
}
const { binding, mode } = options;
const { binding, mode } = { ...emitterDefaults, ...options };
return function emit(event: CloudEvent, opts?: Options): Promise<unknown> {
opts = opts || {};

Expand Down
40 changes: 40 additions & 0 deletions test/integration/emitter_factory_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,46 @@ function gotEmitter(message: Message, options?: Options): Promise<unknown> {
);
}

describe("emitterFor() defaults", () => {
it("Defaults to HTTP binding, binary mode", () => {
function transport(message: Message): Promise<unknown> {
// A binary message will have the source attribute as a header
expect(message.headers[CONSTANTS.CE_HEADERS.TYPE]).to.equal("emitter.test");
return Promise.resolve();
}
const emitter = emitterFor(transport);
emitter(
new CloudEvent({
id: "1234",
source: "/emitter/test",
type: "emitter.test",
}),
);
});

it("Supports HTTP binding, structured mode", () => {
function transport(message: Message): Promise<unknown> {
console.error(message);
// A structured message will have the application/cloudevents+json header
expect(message.headers["content-type"]).to.equal(CONSTANTS.DEFAULT_CE_CONTENT_TYPE);
const body = JSON.parse(message.body as string);
expect(body.id).to.equal("1234");
return Promise.resolve();
}
// Ignore the next line to ensure that HTTP transport is still the default.
// Otherwise, tslint would complain that the param did not have `binding: <val>`
/* @ts-ignore */
const emitter = emitterFor(transport, { mode: Mode.STRUCTURED });
emitter(
new CloudEvent({
id: "1234",
source: "/emitter/test",
type: "emitter.test",
}),
);
});
});

describe("HTTP Transport Binding for emitterFactory", () => {
beforeEach(() => {
nock(sink)
Expand Down