Skip to content

Commit

Permalink
[IMPROVE] Missing addCustomField method in MessageBuilder (#363)
Browse files Browse the repository at this point in the history
* Add custom fields to messageBuilder

* Add tests to the addCustomField method and catch error when key contains a period
  • Loading branch information
matheusbsilva137 committed Dec 13, 2021
1 parent 9a25a73 commit aa7eacf
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/definition/accessors/IMessageBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,4 +221,14 @@ export interface IMessageBuilder {
* Gets the block collection of the message
*/
getBlocks(): Array<IBlock>;

/**
* Adds a custom field to the message.
* Note: This key can not already exist or it will throw an error.
* Note: The key must not contain a period in it, an error will be thrown.
*
* @param key the name of the custom field
* @param value the value of this custom field
*/
addCustomField(key: string, value: any): IMessageBuilder;
}
17 changes: 17 additions & 0 deletions src/server/accessors/MessageBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,4 +200,21 @@ export class MessageBuilder implements IMessageBuilder {
public getBlocks() {
return this.msg.blocks;
}

public addCustomField(key: string, value: any): IMessageBuilder {
if (!this.msg.customFields) {
this.msg.customFields = {};
}

if (this.msg.customFields[key]) {
throw new Error(`The message already contains a custom field by the key: ${ key }`);
}

if (key.includes('.')) {
throw new Error(`The given key contains a period, which is not allowed. Key: ${ key }`);
}

this.msg.customFields[key] = value;
return this;
}
}
6 changes: 6 additions & 0 deletions tests/server/accessors/MessageBuilder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,11 @@ export class MessageBuilderAccessorTestFixture {
Expect(mb.setParseUrls(false)).toBe(mb);
Expect(msg.parseUrls).toEqual(false);
Expect(mb.getParseUrls()).toEqual(false);

Expect(mb.addCustomField('thing', 'value')).toBe(mb);
Expect(msg.customFields).toBeDefined();
Expect(msg.customFields.thing).toBe('value');
Expect(() => mb.addCustomField('thing', 'second')).toThrowError(Error, 'The message already contains a custom field by the key: thing');
Expect(() => mb.addCustomField('thing.', 'second')).toThrowError(Error, 'The given key contains a period, which is not allowed. Key: thing.');
}
}

0 comments on commit aa7eacf

Please sign in to comment.