Saving Data in a Windows 8 JavaScript App

Recently I started to experiment with ESPN’s APIs. You can find them at http://developer.espn.com. You can sign up for an API key for free at the site. I wanted to keep the results being brought back from ESPN by saving the data to disk so I wouldn’t have to continuously hit the ESPN site while I was playing. I figured I would need a settings flag to tell me the last time I hit the ESPN site for data and use file storage to save the results.

The data I was working with was all the sports teams that ESPN had in its database. I didn’t limit it, I just asked for all the sports with this URL: http://api.espn.com/v1/sports followed by my API key. I decided to use the JavaScript Grid App for my testing. This would allow me to return the data and group it by league.

The Grid App gives you a data.js file with some sample data in it. I used that as my template and modified the returned data from ESPN to fit it. Inside the data.js file I replaced the generateSampleData call with my call to the ESPN data using a WinJS.xhr call to retrieve the data into something that I can parse using JSON.parse.

So I changed this:

    // TODO: Replace the data with your real data.
    // You can add data from asynchronous sources whenever it becomes available.
    generateSampleData().forEach(function (item) {
        list.push(item);
    });

To This:

    WinJS.xhr({ url: "http://api.espn.com/v1/sports/?apikey=put your api code here" }).then(function (xhr) {
        var items = JSON.parse(xhr.responseText);
        items.sports.forEach(function (item) {
            if (item.leagues != undefined) {
                var leaguesarray = item.leagues;
                var leagueSport = {
                    key:item.id,
                    title: item.name,
                    subtitle: item.name
                };
                leaguesarray.forEach(function (item) {
                    if (item.shortName != undefined) {
                        switch (item.shortName.substring(0, 4)) {
                            case 'MLB':
                                item.backgroundImage = 'http://upload.wikimedia.org/wikipedia/en/2/2a/Major_League_Baseball.svg';
                                break;
                            case 'NFL':
                                item.backgroundImage = 'http://upload.wikimedia.org/wikipedia/en/1/12/National_Football_League_2008.svg';
                                break;
                            case 'NCAA':
                                item.backgroundImage = 'http://upload.wikimedia.org/wikipedia/commons/d/dd/NCAA_logo.svg';
                                break;
                            case 'NBA':
                                item.backgroundImage = 'http://upload.wikimedia.org/wikipedia/en/0/07/NBALogo.svg';
                                break;
                            case 'WNBA':
                                item.backgroundImage = 'http://upload.wikimedia.org/wikipedia/en/1/1e/Women_National_Basketball_Association.svg';
                                break;
                            default:
                        }
                        item.title = item.shortName;
                        item.group = leagueSport;
                        list.push(item);
                    }
                });
            }

        })
    });

I also added some code to grab logos for some of the leagues from Wikipedia. It wasn’t necessary and they don’t look pretty but it helped me while I was debugging.

So far so good. I can run the code and it will return back teams with their leagues and display them in the grid app. I can even select leagues or individual teams and I will get a page showing up for that league or team.

Now I wanted to add my code to save the data. It appeared that all I would have to do is add a call to create a file and then write to it. First I added the namespaces to my code:

    var applicationData = Windows.Storage.ApplicationData.current;
    var localSettings = applicationData.localSettings;
    var localFolder = applicationData.localFolder;

The I created a function to create the file and write to it. I told the createFileAsync method to overwrite the file if it already existed. The function looked like this (I added some line breaks so you can see most of the code).

    //Store the returned data locally
 function storeESPNData(items) {
     localFolder.createFileAsync("ESPNDataFile.txt",
               Windows.Storage.CreationCollisionOption.replaceExisting)
         .then(function (sampleFile) {
         return Windows.Storage.FileIO.writeTextAsync(sampleFile
, items); }).done(function () { ; }); } }

I added a call to this routine right after the call to JSON.parse.

I tested the code and looked at stored location to see what it had written to the file. The file will be stored in the C:\Users\userid\AppData\Local\Packages\packageguidinfo\LocalState directory. But when I looked at the file in notepad the only thing in it was [object Object].

I was a bit confused for a second until I realized that I had told the system to write out an object but I didn’t tell it to serialize the data. So being the VB/C# programmer that I was, I went looking for the serialize method in JavaScript. That turned out to be a little fruitless but I did come across something called stringify. This appeared be the correct call so I modified my storeESPNData function to call stringify when I called the writeTextAsync method.

The return line now looks like this.

 return Windows.Storage.FileIO.writeTextAsync(sampleFile
                                  , JSON.stringify(items));

After rerunning the code I now have what I was looking for, the entire JSON data stored in a local file. I can now experiment with this data to my hearts content with or without a network connection. The entire code sample (including the extra code to read the local file) can be found on my SkyDrive using this link:

http://sdrv.ms/YOFZJ0

Remember to get your own API code from ESPN and add it to the code.

About these ads

One Response to Saving Data in a Windows 8 JavaScript App

  1. Tyler Dawson says:

    Thanks a million, I’ve been looking for this!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 111 other followers

%d bloggers like this: