attachment-utils.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { Injectable } from '@nestjs/common';
  2. import { Attachment } from 'nodemailer/lib/mailer';
  3. import { Readable } from 'stream';
  4. import { format } from 'url';
  5. import { EmailAttachment, SerializedAttachment } from './types';
  6. export async function serializeAttachments(attachments: EmailAttachment[]): Promise<SerializedAttachment[]> {
  7. const promises = attachments.map(async a => {
  8. const stringPath = typeof a.path === 'string' ? a.path : format(a.path);
  9. return {
  10. filename: null,
  11. cid: null,
  12. encoding: null,
  13. contentType: null,
  14. contentTransferEncoding: null,
  15. contentDisposition: null,
  16. headers: null,
  17. ...a,
  18. path: stringPath,
  19. };
  20. });
  21. return Promise.all(promises);
  22. }
  23. export function deserializeAttachments(serializedAttachments: SerializedAttachment[]): EmailAttachment[] {
  24. return serializedAttachments.map(a => {
  25. return {
  26. filename: nullToUndefined(a.filename),
  27. cid: nullToUndefined(a.cid),
  28. encoding: nullToUndefined(a.encoding),
  29. contentType: nullToUndefined(a.contentType),
  30. contentTransferEncoding: nullToUndefined(a.contentTransferEncoding),
  31. contentDisposition: nullToUndefined(a.contentDisposition),
  32. headers: nullToUndefined(a.headers),
  33. path: a.path,
  34. };
  35. });
  36. }
  37. function nullToUndefined<T>(input: T | null): T | undefined {
  38. return input == null ? undefined : input;
  39. }