Lesson 08: Getting People Data

From VZ Developer Wiki
Jump to: navigation, search

General Guidelines | XML Specification | Features | Views | JavaScript API | REST API | Tutorials | OAuth


Lesson 07: Gadget Localization Back to overview Lesson 09: Storing and Retrieving AppData

In this section we will create a gadget that will list all of the current viewer's friends.

When you are using OpenSocial Features to retrieve user data, you should specify the fields your gadget initially requires (see OpenSocial_RequiredFields). When the user installs your gadget he is the only prompted to fill out these fields in his vcard. Of course you can change the permission later on with a new revision or dynamically through a JavaScript method (see Lesson_16:_Request_additional_data_from_your_user).

First, create a function that is called once the gadget is loaded. For now, it, will only perform one job, but later will start multiple steps for initialization.

gadgets.util.registerOnLoadHandler(init);

function init() {
  loadFriends();
}

Now, of course, there needs to be a function to actually load the friend data. The following function creates a new data request object, then populates it with specific types of data that you'll need: the viewer and the viewer's friends. Notice that in order to request friends, the code constructs an IdSpec object. An IdSpec is used when you need to specify one or more people in a group (in this case, the viewer's friends). Then, it sends the request to the server, and gives it the name of a function to call when the data is returned.

function loadFriends() {
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
  
  var viewerFriends = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
  var opt_params = {};
  opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 100;
  req.add(req.newFetchPeopleRequest(viewerFriends, opt_params), 'viewerFriends');

  req.send(onLoadFriends);
}

The callback function, onLoadFriends, will take the data that the server has returned, and display it on the page. The simple check for person.getId() assures that only mutual friends are loaded.

function onLoadFriends(data) {
  var viewer = data.get('viewer').getData();
  var viewerFriends = data.get('viewerFriends').getData();

  html = new Array();
  html.push('<ul>');
  viewerFriends.each(function(person) {
    if (person.getId()) {
      html.push('<li>' + person.getDisplayName() + "</li>");
    }
  });
  html.push('</ul>');
  document.getElementById('friends').innerHTML = html.join('');
}

Several div elements have been inserted within the gadget specification as entry points for the new HTML.

<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs title="Gifts part 1 - Friends">
    <Require feature="opensocial-0.8"/>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[
      <script type="text/javascript">
        /* ... */
      </script>
      '''<div id='main'>
        Your friends:
        <div id='friends'></div>
      </div>
    ''']]>
  </Content>
</Module>

New OSAPI

OpenSocial 0.9 introduces a new JavaScript API, that makes retrieving social data much easier and more streamlined:

osapi.people.get({userId: '@VIEWER', groupId: '@FRIENDS'}).execute(function(data) {
  if (data.error) {
    alert('Error occurred: ' + data.error.message);
  } else {
    alert('You have ' + data.length + ' friends');
  }

});
osapi.people.get({userId: 'www.vz.net:ahbaobhaba', groupId: '@FRIENDS'}).execute(function(data) {
  if (data.error) {
    alert('Error occurred: ' + data.error.message);
  } else {
    alert('User has ' + data.length + ' friends');
  }
});

Of course you can also batch these requests into one HTTP request:

osapi.newBatch().
   add('viewer_friends', osapi.people.get({userId: '@VIEWER', groupId: '@FRIENDS'})).
   add('user_friends', osapi.people.get({userId: 'www.vz.net:ahbaobhaba', groupId: '@FRIENDS'})).
   execute(function(result) {
    if (result.error) {
      alert("This batch had an error: " + result.error.message);
    } else {
      alert(result.viewer_friends.length);
      alert(result.user_friends.length);
    }

   });

Data Pipelining

You can also use data pipelining to prefetch user data that can then be used in OpenSocial Templates or accessed by the JavaScript API:

<Content type="html"><![CDATA[ 
  <script xmlns:os="http://ns.opensocial.org/2008/markup" type="text/os-data">
    <os:PeopleRequest key="vf" userId="@viewer" groupId="@friends"/>
  </script>
  <script type="text/os-template">
    <div repeat="${vf}">${Name} is a friend.</div>
  </script>
]]>
</Content>

See Data_Pipelining for details.


  • Lesson 08: Getting People Data