How to extract a parsed email address from a LinkedIn API response?

  auth0, javascript, linkedin-api

I’m trying to setup a custom Auth0 LinkedIn Connection.

This is what I have for the Fetch User Profile Script:

function fetchUserProfile(accessToken, context, callback) {

  //Create the profile object
  const profile = {
    user_id: '',
    given_name: '',
    family_name: '',
    email: '',
  };

  // Call the Linkedin Primary Contact API
  request.get(
    {
      url: 'https://api.linkedin.com/v2/me',
      headers: {
        'Authorization': 'Bearer ' + accessToken,
      }
    },
    (err, resp, body) => {
      if (err) {
        return callback(err);
      }

      if (resp.statusCode !== 200) {
        return callback(new Error(body));
      }

      let bodyParsed;
      try {
        bodyParsed = JSON.parse(body);
      } catch (jsonError) {
        return callback(new Error(body));
      }

      profile.user_id = bodyParsed.id;
      profile.given_name = bodyParsed.localizedFirstName;
      profile.family_name = bodyParsed.localizedLastName;

    }
  );
  
  // Call the Linkedin Profile API
  request.get(
    {
      url: 'https://api.linkedin.com/v2/clientAwareMemberHandles?q=members&projection=(elements*(primary,type,handle~))',
      headers: {
        'Authorization': 'Bearer ' + accessToken,
      }
    },
    (err, resp, body) => {
      if (err) {
        return callback(err);
      }

      if (resp.statusCode !== 200) {
        return callback(new Error(body));
      }

      let bodyParsed;
      try {
        bodyParsed = JSON.parse(body);
      } catch (jsonError) {
        return callback(new Error(body));
      }
    console.log(body);
    profile.email = bodyParsed.elements.handle~.emailAddress;

    }
  );

  //Send the profile object to the callback
  callback(null, profile);

}

It works (almost) but I’m having trouble putting emailAddress into the profile object.

The console.log(body); returns something like this (email redacted):

{
   "elements":[
      {
         "handle":"urn:li:emailAddress:102319820",
         "type":"EMAIL",
         "handle~":{
            "emailAddress":"[email protected]"
         },
         "primary":true
      }
   ]
}

The problem is that profile.email = bodyParsed.elements.handle~.emailAddress; gives an error because it uses the ~ symbol.

So how do I access emailAddress and insert it into the profile object?

Source: Ask Javascript Questions

LEAVE A COMMENT