Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: don't require a data attribute to be passed when sending a message #1370

Merged
merged 2 commits into from
Aug 19, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 12 additions & 2 deletions src/publisher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,21 @@ export class Publisher {
publishMessage(message: PubsubMessage, callback: PublishCallback): void {
const {data, attributes = {}} = message;

if (!(data instanceof Buffer)) {
// We must have at least one of:
// - `data` as a Buffer
// - `attributes` that are not empty
if (data && !(data instanceof Buffer)) {
throw new TypeError('Data must be in the form of a Buffer.');
}

for (const key of Object.keys(attributes!)) {
const keys = Object.keys(attributes!);
if (!data && keys.length === 0) {
throw new TypeError(
'If data is undefined, at least one attribute must be present.'
);
}

for (const key of keys) {
const value = attributes![key];
if (typeof value !== 'string') {
throw new TypeError(`All attributes must be in the form of a string.
Expand Down
12 changes: 12 additions & 0 deletions test/publisher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,18 @@ describe('Publisher', () => {
);
});

it('should throw an error if data and attributes are both empty', () => {
assert.throws(
() => publisher.publishMessage({}, spy),
/at least one attribute must be present/
);
});

it('should allow sending only attributes', () => {
const attributes = {foo: 'bar'} as {};
assert.doesNotThrow(() => publisher.publishMessage({attributes}, spy));
});

it('should throw an error if attributes are wrong format', () => {
const attributes = {foo: {bar: 'baz'}} as {};

Expand Down