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

[IMPROVE] Missing addCustomField method in MessageBuilder #363

Merged
merged 4 commits into from
Dec 13, 2021
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
10 changes: 10 additions & 0 deletions src/definition/accessors/IMessageBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,4 +212,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 @@ -192,4 +192,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;
d-gubert marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -104,5 +104,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.');
}
}