Skip to content

Commit

Permalink
fix: don't require a data attribute to be passed when sending a mes…
Browse files Browse the repository at this point in the history
…sage (#1370)

Fixes #1363

We chatted about this and came to the conclusion that the Node library is probably just wrong here.
  • Loading branch information
feywind committed Aug 19, 2021
1 parent d869641 commit 97fd4f0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
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

0 comments on commit 97fd4f0

Please sign in to comment.