Skip to content

Commit

Permalink
Refactor Attachment class create method for Mail class
Browse files Browse the repository at this point in the history
  • Loading branch information
usualdesigner committed Jun 18, 2024
1 parent 07b4f71 commit e027c48
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
2 changes: 2 additions & 0 deletions packages/helpers/classes/attachment.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,6 @@ export default class Attachment implements AttachmentData {
setDisposition(disposition: string): void;
setContentId(contentId: string): void;
toJSON(): AttachmentJSON;
static create(data: AttachmentData | Attachment): Attachment;
static create(data: AttachmentData[] | Attachment[]): Attachment[];
}
13 changes: 13 additions & 0 deletions packages/helpers/classes/attachment.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,19 @@ class Attachment {
//Return
return toSnakeCase(json);
}

static create(data) {
if(Array.isArray(data)) {
return data.filter(Boolean).map(item => this.create(item));
}
//Already instance of Attachment class?
if (data instanceof Attachment) {
return data;
}

//Create instance
return new Attachment(data);
}
}

//Export class
Expand Down
3 changes: 2 additions & 1 deletion packages/helpers/classes/mail.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
const EmailAddress = require('./email-address');
const Personalization = require('./personalization');
const Attachment = require('./attachment');
const toCamelCase = require('../helpers/to-camel-case');
const toSnakeCase = require('../helpers/to-snake-case');
const deepClone = require('../helpers/deep-clone');
Expand Down Expand Up @@ -388,7 +389,7 @@ class Mail {
if (!attachments.every(attachment => !attachment.disposition || typeof attachment.disposition === 'string')) {
throw new Error('Expected the attachment\'s `disposition` field to be a string');
}
this.attachments = attachments;
this.attachments = Attachment.create(attachments);
}
}

Expand Down
17 changes: 17 additions & 0 deletions packages/helpers/classes/mail.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,23 @@ describe('Mail', function() {
}],
})).to.throw('filename');
});

it('properly handles attachment contentId', () => {
const contentId = 'test-content-id';
const mail = new Mail({
to: '[email protected]',
attachments: [{
disposition: 'inline',
content: 'test-content',
filename: 'name-that-file',
type: 'file-type',
contentId,
}],
});
const mainJSON = mail.toJSON();
const firstAttachment = mainJSON.attachments[0];
expect(firstAttachment.content_id).to.equal(contentId);
});
});
});

Expand Down

0 comments on commit e027c48

Please sign in to comment.