Tài liệu Building OpenSocial Apps- P2 pdf

50 305 0
Tài liệu Building OpenSocial Apps- P2 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

ptg 24 Chapter 2 Getting Basic MySpace Data Error Handling JavaScript errors from apps seem to be an all-too-common occurrence, but they don’t have to be. Most developers don’t expect errors to occur, and so they don’t test or pre- pare for them as a result, but errors do happen.Your best defense against them is to admit that yes, they do occur, and yes, you need to be ready for them. OpenSocial offers a few functions you can use to deal with errors. In the following example we check for errors before we parse the response for data. If an error is found, the response data isn’t parsed. /** * Check if the response had an error; if it did, log it and if * it was an INTERNAL_ERROR attempt to retry the request * @param {opensocial.DataResponse} data */ function requestHadError(data){ // Return true if data is null or undefined if(!data) return true; // Check the opensocial.DataResponse for the global error flag if(data.hadError()){ // Find the specific opensocial.ResponseItem that had the error var ri = data.get(Tic-Tac-Toe.RequestKeys.VIEWER); // If the view name passed in is in the supported hash table if(supported[view]){ // Request to navigate to that view gadgets.views.requestNavigateTo(supported[view]); } } This function takes in the name of the view to navigate to and then gets the list of currently supported views by calling gadgets.views.getSupportedViews() . This function returns a hash table of gadgets.views.View objects, keyed by the names of the views. If the list of supported views contains the specified view, requestNavigateTo is invoked and the View object is passed in. To make use of the rNT function, you might do something like this in the onclick handler of a button: rNT(gadgets.views.ViewType.CANVAS); That will cause the browser to navigate to the app’s Canvas page. 24 Chapter 2 Getting Basic MySpace Data From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 25 if(ri && ri.hadError()){ // Output the error message log(ri.getErrorMessage()); // Check the error code; an INTERNAL_ERROR can simply mean // network congestion or MySpace server instability if(opensocial.ResponseItem.Error.INTERNAL_ERROR === ri.getErrorCode()){ // Retry the request a certain number of times; make // sure you don't create an infinite loop here! if(retries > 0){ retries--; window.setTimeout(getInitialData, 1000); } } } return true; } return false; } First, we check if the response is null or undefined, and then check if the global error flag was set in the DataResponse object by calling the object’s hadError() function. This flag is set if any of the requests had an error. Each ResponseItem has an error flag as well, so we’ll need to check each ResponseItem in order to find out which request had the error, if the global flag was set. We do this by calling the ResponseItem ’s hadError() function. In this case we had only one request, so there is only one ResponseItem , but in the event of multiple ResponseItem objects we would check each one in turn to determine its error state. Similar to an opensocial.Enum object that has two types of data, one for display and one for logical comparisons, each opensocial.ResponseItem that encounters an error also has two types of data.The error message, accessed by getErrorMessage() , is an arbitrary string that should describe the error and help you debug what happened.The error code, accessed by getErrorCode() , matches up to one of the codes found in the opensocial.ResponseItem.Error enum. Common causes for each type of error code may be found in Table 2.4. You’ll notice that we also attempted to retry the request in the event of an INTERNAL_ERROR .This is because an INTERNAL_ERROR can sometimes occur because of network congestion or other temporary problems.Your request might succeed if you wait a second or so and try again. Error Handling 25 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 26 Chapter 2 Getting Basic MySpace Data Handling errors offers two benefits: n There are no embarrassing JavaScript errors when you try to retrieve objects that don’t exist. n There’s a possibility that you can recover from your error by retrying the request. Table 2.4 Common Error Code Causes Common Error Codes Causes opensocial.ResponseItem.Error. The most common cause of this error is that BAD_REQUEST some part of your request didn’t make sense to the container. For example, you passed in a negative value that should be positive, you didn’t supply a required field, or you passed in an invalid ID for a particu- lar request. opensocial.ResponseItem.Error. This error is returned only when the server FORBIDDEN responds with a status code of 403 and is not commonly seen. opensocial.ResponseItem.Error. This is a catchall error that typically occurs INTERNAL_ERROR when something unknown happens on the MySpace side of the request. As such, it should be intermittent. It can also occur in opensocial.requestPermission (a topic we’ll cover in the section on requesting per- missions in Chapter 3) if a permission was requested but no new permission was granted, or if the server returned an unknown status code. opensocial.ResponseItem.Error. This error is returned if you’ve requested NOT_IMPLEMENTED some OpenSocial functionality that MySpace doesn’t support. If you receive this error, either the entire function you’re calling isn’t available, or some parameter in a request isn’t supported. An example of the latter would be that you requested an opensocial.Person field that isn’t supported. opensocial.ResponseItem.Error. This error most commonly happens when UNAUTHORIZED you’ve requested data to which you don’t have access. It may be possible to use opensocial.requestPermission to ask the user to grant your app access to the data. Again, see Chapter 3 for details. 26 Chapter 2 Getting Basic MySpace Data From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg Warning When retrying your request after an error, be careful you don’t code yourself into an infinite loop! It’s best to keep a retry counter as we do in the code shown previously. Summary In this chapter we covered the basic flow of an OpenSocial application, focusing on the process of accessing data on the API and OpenSocial’s request/response pattern.We also defined an opensocial.Person object—what it is, how to get it, and what to do with it. This request/response pattern is the foundation of any OpenSocial app.You will use it every time you request data from the server, so we hope you were paying attention. Note Code listings and/or code examples for this chapter and every other chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com. 27 Summary 27 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg This page intentionally left blank From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 3 Getting Additional MySpace Data I n the preceding chapter we covered how to fetch and make use of the Person object on the MySpace platform. But there’s a lot more data out there—such as the user’s friend list and the photos the user has uploaded. It’s the use of all this data that will propel your app from a lifeless Web game to a dynamic and social application with viral potential. Most application developers use the friend list in order to spread and share their applications (see Chapter 5, Communication and Viral Features, to learn how) and other endpoints like albums and videos to make their apps more personal and engaging for the user. In this chapter we’ll do just that by covering how to access and use your users’ data to make your app more dynamic and appealing.We’ll show how to retrieve your users’ friends; use paging to sort, sift, and display the data; as well as explore viewing albums, photos, and videos.We’ll also discuss some extras, such as how to check whether a user already has an app installed and how to check for and request permissions from a user. As we start to request more and more sensitive data, such as a user’s photos, permissions will start to come into play more and more. From now on, our Tic-Tac-Toe game is no longer a boring JavaScript applet. It’s a feature-packed app that actually uses the power of the MySpace social network. How to Fetch a Friend List and Make Use of the Data This section will show you how to fetch a list of friends and then page through that list. You’ll also learn the various ways you can sort and filter a friend list, such as restricting it to only friends who have the app installed. From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg In our example Tic-Tac-Toe app, we’ll use the list of friends in two ways: n Provide a list of all the Viewer’s friends so the Viewer can send invitations to those friends to add the app. n Provide a list of friends who already have the app installed so the Viewer can challenge those friends to a game of Tic-Tac-Toe. The actual invitation sending and game play challenges will be covered in Chapter 5, Communication and Viral Features.This section will lay the foundation for those functions by showing you how to pull out the friend list and filter it accordingly. A Quick JavaScript Lesson Up until now, we’ve kept the code simple by sticking to OpenSocial-specific JavaScript. We did this by separating the Tic-Tac-Toe game logic from the OpenSocial code and keep- ing everything globally namespaced (meaning the code can be called from anywhere; this is its “scope” in programming terms). Moving forward, our app will become more and more complex. This added complexity requires us to start introducing more advanced JavaScript techniques such as object notation and object-oriented programming. This is not a book on JavaScript programming but on how to build dynamic OpenSocial apps on MySpace. You’ll find, however, that you’ll learn a lot about JavaScript along the way! To this end you’ll start to notice the use of the TTT namespace. This is where we’ll keep all the code for game-specific functionality. For example, in Chapter 2, Getting Basic MySpace Data, we provided a key of "v" when we requested the Viewer data. In this chapter we move all of those keys into an enum: TTT.RequestKeys . So instead of using key "v" , we use key TTT.RequestKeys.VIEWER . We concentrate on the OpenSocial code in this book, but feel free to dig into the full code listings found at our Google Code site: http://opensocialtictactoe.googlecode.com. Getting the Friend List This is the same request/response idea from Chapter 2, Getting Basic MySpace Data, that helps define OpenSocial. In fact, the friend list is just an opensocial.Collection of opensocial.Person objects, but instead of dealing with just one Person as in Chapter 2, we’re dealing with a list of them. There are two major differences between fetching a single Person and fetching a friend list: n Call newFetchPeopleRequest instead of newFetchPersonRequest . n Instead of passing in an ID (such as Viewer or Owner), pass in an opensocial.IdSpec object. An IdSpec object is a different way to specify a group of IDs. It requires you to define two parameters: the user ID and the network distance.The user ID specifies the 30 Chapter 3 Getting Additional MySpace Data From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg context for the IdSpec —basically letting MySpace know if you’re asking for a group involving the Owner or the Viewer. MySpace supports the contexts of only Viewer and Owner. In other words, you can’t get a friend list for a random user; it has to be for either the Viewer or the Owner. The network distance defines how far out the connections go. For example, specify- ing a network distance of 0 would denote just the Owner or the Viewer, and a network distance of 1 would denote the friends of the Owner or the Viewer. At this time MySpace supports a network distance only to a maximum of 1, so you can’t fetch the friends of your friends. Let’s create a fetchFriendList() function to get a basic friend list.This function wraps the newFetchPeopleRequest . Our example is heavily simplified, though, so it isn’t our final version of the function. We’ll expand on it as we see what else you can do with a friend list. We’ll be inserting this function into the code of our Tic-Tac-Toe app found in Chapter 2. For those of you following along at home, place this function anywhere in the script tag in that code: function fetchFriendList(callback){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1; var idspec = opensocial.newIdSpec(params); // Create the DataRequest object var request = opensocial.newDataRequest(); // Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS); // Send it off request.send(callback); } First, the IdSpec object is created using a user ID of VIEWER and a network distance of 1 to specify that we want the friends of the Viewer. Next, an opensocial.DataRequest object is instantiated and the request is added to the queue with a custom key of TTT.RequestKeys.VIEWER_FRIENDS . Finally, the request is sent off (and the response will find its way back to the specified callback). Filters and Sorts The first example we showed you just fetches an arbitrary subset of friends of the Viewer. This list is typically returned in the order in which the friendships were made and is not How to Fetch a Friend List and Make Use of the Data 31 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg terribly complex. OpenSocial, however, defines a number of ways to sort and filter fetched lists, making them a lot more useful. Before getting to the code, let’s look at the available options.The MySpace-supported filter types and sorts are shown in Table 3.1. Let’s revisit the fetchFriendList() function, but this time with support for sorts and filters. Again, we’re not quite at the final version of our function, but this code brings us a step closer: function fetchFriendList(callback, filter, sort){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1; var idspec = opensocial.newIdSpec(params); params = {}; // Add any filters if(filter && filter.length > 0){ params[opensocial.DataRequest.PeopleRequestFields.FILTER] = filter; } // Add any sorts if(sort && sort.length > 0){ params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = sort; } // Create the DataRequest object var request = opensocial.newDataRequest(); // Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS); // Send it off request.send(callback); } You can see that the filters and sorts are specified by adding opensocial. DataRequest.PeopleRequestFields.FILTER and opensocial.DataRequest. PeopleRequestFields.SORT_ORDER to the parameters. Paging According to the OpenSocial spec, the default number of items returned for a request is 20. That means our fetchFriendList() function returns the first 20 friends in the list. But what if a user has more than 20 friends? Enter paging. 32 Chapter 3 Getting Additional MySpace Data From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg Paging is a way to get a large collection of data one chunk at a time.That means that once we have fetched friends 1 to 20, we can then fetch friends 21 to 40, then 41 to 60, and so on. OpenSocial also provides a way to specify which chunk of friends you want for a given request. To demonstrate paging, let’s expand one final time on our fetchFriendList() function: function fetchFriendList(first, max, callback, filter, sort){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; Table 3.1 Supported Friend List Filters and Sorts on MySpace Filter Type Details opensocial.DataRequest.FilterType. The default filter, essentially no filter ALL opensocial.DataRequest.FilterType. Fetches only those friends who have HAS_APP added the app opensocial.DataRequest.FilterType. MySpace allows users to define top or TOP_FRIENDS favorite friends; these are the friends who appear at the top of the user’s Friend Space, and this filter fetches only those friends. MyOpenSpace.DataRequest.FilterType. Fetches only friends who ONLINE_FRIENDS are currently online MyOpenSpace.DataRequest.SortOrder.ID Not a filter; allows you to sort a friend list by ID (ascending). Note that this sort is applied after the page is fetched, so it doesn’t take the user’s entire friend list, sort it, and return a particular page. What happens is that a page of friends is taken and that list is sorted. This is not particularly useful. opensocial.DataRequest.SortOrder.NAME Another sort; sorts the returned list by nickname (ascending). Like the pre- ceding sort, this one isn’t the most useful as the entire friend list isn’t sorted up front, only the returned page. How to Fetch a Friend List and Make Use of the Data 33 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... req = opensocial. newDataRequest(); if(fields == null){ fields = "*"; //Default to all data } var idparams = {}; idparams [opensocial. IdSpec.Field.USER_ID] = opensocial. IdSpec.PersonId.VIEWER; idparams [opensocial. IdSpec.Field.NETWORK_DISTANCE] = 0; var id = opensocial. newIdSpec(idparams); req.add(req.newFetchPersonAppDataRequest (id, fields), appdataKey); Please purchase PDF Split-Merge on www.verypdf.com... page under http://opensocialtictactoe.googlecode.com Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark From the Library of Lee Bogdanoff This page intentionally left blank Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark From the Library of Lee Bogdanoff 4 Persisting Information As your ambitions foryou’ll have is persisting with OpenSocial grow,sessions.Without... setAppDataKey(key, value, callback) { var req = opensocial. newDataRequest(); req.add(req.newUpdatePersonAppDataRequest( opensocial. IdSpec.PersonId.VIEWER, key, value), "set_" + key); req.send(callback); }; /** * Get the discrete app data and initialize the view */ function getInitialData(){ var req = opensocial. newDataRequest(); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark From... TTT.Keys.NAME, TTT.Keys.SCORE ]; var idparams = {}; idparams [opensocial. IdSpec.Field.USER_ID] = opensocial. IdSpec.PersonId.VIEWER; idparams [opensocial. IdSpec.Field.NETWORK_DISTANCE] = 0; var id = opensocial. newIdSpec(idparams); req.add(req.newFetchPersonAppDataRequest( id, fields), TTT.RequestKeys.VIEWERDATA); if(viewer == null){ req.add(req.newFetchPersonRequest( opensocial. IdSpec.PersonId.VIEWER), TTT.RequestKeys.VIEWER);... Additional MySpace Data params [opensocial. IdSpec.Field.NETWORK_DISTANCE] = 1; var idspec = opensocial. newIdSpec(params); params = {}; // Set the paging parameters if(first){ params [opensocial. DataRequest.PeopleRequestFields.FIRST] = first; } if(max){ params [opensocial. DataRequest.PeopleRequestFields.MAX] = max; } // Add any filters if(filter && filter.length > 0){ params [opensocial. DataRequest.PeopleRequestFields.FILTER]... discrete app data and initialize the view */ function getInitialAppDataV1(){ var req = opensocial. newDataRequest(); var fields = [ TTT.Keys.NAME, TTT.Keys.SCORE ]; var idparams = {}; idparams [opensocial. IdSpec.Field.USER_ID] = opensocial. IdSpec.PersonId.VIEWER; idparams [opensocial. IdSpec.Field.NETWORK_DISTANCE] = 0; var id = opensocial. newIdSpec(idparams); req.add(req.newFetchPersonAppDataRequest (id, fields),... opt_params) id is a string used to identify who owns the videos.The value can be either opensocial. IdSpec.PersonId.VIEWER or opensocial. IdSpec.PersonId.OWNER opt_params is an object map that specifies optional parameters In this case, only the paging parameters are allowed: opensocial. DataRequest.PeopleRequestFields FIRST and opensocial. DataRequest.PeopleRequestFields.MAX Since the implementation of both the... is so similar to that of photos, which we’ve already discussed, we leave it to you to experiment with these as you wish Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark From the Library of Lee Bogdanoff Using opensocial. requestPermission and opensocial. hasPermission Table 3.4 Fields for the MyOpenSpace.Video Object Field Description VIDEO_ID The ID number—a video’s unique identifier... we get the photos? if (opensocial. hasPermission(perm)){ // Yep fetchPhotos(TTT.ListTypes.SET_BACKGROUND); } Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark From the Library of Lee Bogdanoff 44 Chapter 3 Getting Additional MySpace Data else{ // We can't; let's request the permission to do so var reason = "To set a custom background for the game board!"; opensocial. requestPermission([perm],... sort.length > 0){ params [opensocial. DataRequest.PeopleRequestFields.SORT_ORDER] = sort; } // Create the DataRequest object var request = opensocial. newDataRequest(); // Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS); // Send it off request.send(callback); } You’ll notice that opensocial. DataRequest.PeopleRequestFields.FIRST and opensocial. DataRequest.PeopleRequestFields.MAX . params [opensocial. IdSpec.Field.USER_ID] = opensocial. IdSpec.PersonId.VIEWER; params [opensocial. IdSpec.Field.NETWORK_DISTANCE] = 1; var idspec = opensocial. newIdSpec(params);. params [opensocial. IdSpec.Field.USER_ID] = opensocial. IdSpec.PersonId.VIEWER; params [opensocial. IdSpec.Field.NETWORK_DISTANCE] = 1; var idspec = opensocial. newIdSpec(params);

Ngày đăng: 24/12/2013, 06:17

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan