HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/good-life-be/node_modules/@sendgrid/helpers/classes/email-address.js
'use strict';

/**
 * Dependencies
 */
const splitNameEmail = require('../helpers/split-name-email');

/**
 * Email address class
 */
class EmailAddress {

  /**
	 * Constructor
	 */
  constructor(data) {

    //Construct from data
    if (data) {
      this.fromData(data);
    }
  }

  /**
   * From data
   */
  fromData(data) {

    //String given
    if (typeof data === 'string') {
      const [name, email] = splitNameEmail(data);
      data = {name, email};
    }

    //Expecting object
    if (typeof data !== 'object') {
      throw new Error('Expecting object or string for EmailAddress data');
    }

    //Extract name and email
    const {name, email} = data;

    //Set
    this.setEmail(email);
    this.setName(name);
  }

  /**
   * Set name
   */
  setName(name) {
    if (typeof name === 'undefined') {
      return;
    }
    if (typeof name !== 'string') {
      throw new Error('String expected for `name`');
    }
    this.name = name;
  }

  /**
   * Set email (mandatory)
   */
  setEmail(email) {
    if (typeof email === 'undefined') {
      throw new Error('Must provide `email`');
    }
    if (typeof email !== 'string') {
      throw new Error('String expected for `email`');
    }
    this.email = email;
  }

  /**
	 * To JSON
	 */
  toJSON() {

    //Get properties
    const {email, name} = this;

    //Initialize with mandatory properties
    const json = {email};

    //Add name if present
    if (name !== '') {
      json.name = name;
    }

    //Return
    return json;
  }

  /**************************************************************************
   * Static helpers
   ***/

  /**
   * Create an EmailAddress instance from given data
   */
  static create(data) {

    //Array?
    if (Array.isArray(data)) {
      return data
        .filter(item => !!item)
        .map(item => this.create(item));
    }

    //Already instance of EmailAddress class?
    if (data instanceof EmailAddress) {
      return data;
    }

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

//Export class
module.exports = EmailAddress;