Tutorial build - ncmcgrewdev/fs-js-lite GitHub Wiki

Step 3: Build and Run the Tutorial App

NOTE: You must complete the previous steps of this tutorial before proceeding.

This tutorial app will get you started with the FamilySearch JavaScript SDK Lite.

To complete the tutorial you will be editing the index.html file.

Setup html and JavaScript files

  1. Create the following files with the indicated content:

public/index.html

<!DOCTYPE html>

<!-- define angular app -->
<html ng-app="myApp">
<head>
<!-- SCROLLS -->
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

<!-- SPELLS -->
<!-- load angular via CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="https://unpkg.com/fs-js-lite@latest/dist/FamilySearch.min.js"></script>
<script src="javascripts/controller.js"></script>
</head>
<body>
  <div id="main">
    <div ng-view></div>
  </div>
</body>
</html>

public/pages/home.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Home</title>
  </head>
  <body>
    <div>
      <div>
        <button ng-click="login()">Login with FamilySearch</button>
        <p>{{ message }}</p>
      </div>
    </div>
  </body>
</html>

public/javascripts/controller.js

// CLIENT OBJECT GOES HERE

var myApp = angular.module('myApp', ['ngRoute']);

// configure our routes
myApp.config(function ($routeProvider) {
  $routeProvider
  
  // route for the home page
    .when('/', {
      templateUrl: 'pages/home.html',
      controller: 'loginController'
    });
});

// create the controller and inject Angular's $scope
myApp.controller('loginController', function ($scope, $location) {
  // AUTHENTICATE
});
  1. In a browser, load http://localhost:3000, then return to these instructions.

Authenticate with FamilySearch

Your app must first authenticate a user with FamilySearch. To authenticate you must use an app key that is assigned to your app by FamilySearch. This app key is used to obtain an access token which is required by each FamilySearch API endpoint.

  1. Insert the following object at the top of the controller.js file in the Client section:
var client = new FamilySearch({
  environment: 'integration',
  appKey: 'YOUR APP KEY', // you get this from your FamilySearch developer account
  redirectUri: 'http://localhost:3000',
  saveAccessToken: true,
  tokenCookie: 'FS_AUTH_TOKEN',
  maxThrottledRetries: 10,
  pendingModifications: ['consolidate-redundant-resources', 'another-pending-mod'],
  requestInterval: 1000
});
  1. Find your app key in the FamilySearch Developer website on the My Apps page.

  2. Copy your app key into the designated line of the CLIENT object.

  3. Insert the following AUTHENTICATE code into the controller.js file.

// This redirects to the FamilySearch login page
$scope.login = function () {
  window.location.href = client.oauthRedirectURL();
}

// After you login, FamilySearch redirects you to the redirect URI specified in the client object
// At this point, the token will be encoded as a URL parameter, so we use the following functions to parse and decode the access token
$scope.checkAccessToken = function () {
  var url = $location.absUrl().split('?');
  if (url.length > 1) {
    getParameterByName('code');
  }
  else if (typeof(Storage) !== "undefined" && localStorage.getItem('fs_access_token')) {
    client.setAccessToken(localStorage.getItem('fs_access_token'));
    console.log("already logged in!")
  }
  
}

var getParameterByName = function (name) {
  var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  var accessToken =  match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  
  localStorage.setItem("fs_access_token", accessToken);
  
  console.log("Congratulations!  You're logged in!")
}
  1. Update home.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Home</title>
  </head>
  <body>
    <div data-ng-init="checkAccessToken()">
      <div>
        <button ng-click="login()">Login with FamilySearch</button>
        <p>{{ message }}</p>
      </div>
    </div>
  </body>
</html>
  1. Save controller.js and refresh the browser page that is running it. To test that your code is working, login using the Integration Account information found in your FamilySearch Developer account.

Read the Current Tree Person

With your access token you can now use any of the methods in the JavaScript SDK. Start by reading the current person in the FamilySearch Tree.

  1. Insert the following READ CURRENT TREE PERSON code into the tutorial.html file.
<script>    // Get the current tree person.
  var readPerson = function (){
    // From the user profile, extract the tree person ID.
    client.getCurrentUser().then(function(userResponse){
      return userResponse.getUser().getPersonId();
    })

    // Retrieve the person
    .then(function(personId){
      return client.getPerson(personId);
    })

    // Get the person from the response and print
    .then(function(personResponse){
      var person = personResponse.getPerson();
      $('#read-person').append('<b>Name: </b>'+person.getDisplayName()+'<br><strong>Birth Date: </strong>'+person.getDisplayBirthDate()+'<br><br>Now update the tutorial app to SEARCH.');
    })

    // Catch any errors
    .catch(function(e){
      $('#read-person').append(displayError(e));
    });
  }
</script>
<a href="#" onclick="readPerson()"><h2>Click to READ THE CURRENT TREE PERSON</h2></a><br><br>
<div id="read-person"></div>

  1. Save tutorial.html and refresh the browser page that is running it.

Search for People in the Tree

You can specify search criteria to perform a search for people in the tree.

  1. Insert the following SEARCH code into the tutorial.html file. There are many search and display options you can program. This tutorial shows only a few.
<h2>SEARCH FOR PEOPLE IN THE TREE </h2>
<div>
  <div class="row">
    <div class="form-group col-sm-6">
      <label for="givenName">Given Name</label>
      <input type="text" class="form-control" id="givenName" placeholder="given name">
    </div>
    <div class="form-group col-sm-6">
      <label for="surname">Surname</label>
      <input type="text" class="form-control" id="surname" placeholder="surname">
    </div>
    <div class="form-group col-sm-6">
      <label for="birthDate">Birth Date</label>
      <input type="text" class="form-control" id="birthDate" placeholder="birth date">
    </div>
  <p class="text-center"><button id="searchButton" class="btn btn-primary">Search</button></p>
  </div>
</div>

<div id="search-results"></div>

<script> // Search the tree for people
  var $content = $('#search-results');

  // Search when the user clicks on the button.
  $('#searchButton').click(function(){
    $content.html('');    
    var params = {
      givenName: $('#givenName').val(),
      surname: $('#surname').val(),
      birthDate: $('#birthDate').val(),
    };
  
    client.getPersonSearch(params).then(function(searchResponse){   
      $('<h3>').text('Results').appendTo($content);
      var $table = $('<table>').addClass('table');
      $table.append(
        $('<tr>')
          .append('<th>Id</th>')
          .append('<th>Name</th>')
          .append('<th>Birth</th>')
          .append('<th>Death</th>')
      );
    
      var results = searchResponse.getSearchResults();
      for(var i = 0; i < results.length; i++){
        var result = results[i],
            person = result.getPrimaryPerson(),
            $row = $('<tr>').appendTo($table);
        $('<td>').text(person.getId()).appendTo($row);
        $('<td>').text(person.getDisplayName()).appendTo($row);
        $('<td>').text(person.getDisplayBirthDate()).appendTo($row);
        $('<td>').text(person.getDisplayDeathDate()).appendTo($row);
      }
    
      $content.append($table);
      $content.append('<br><br>Now update the tutorial app to READ PID.');
    
    })
    
    // Catch any errors
    .catch(function(e){
      $loader.hide();
      $content.append(displayError(e));
    });
  })
</script>

  1. Save tutorial.html and refresh the browser page that is running it.
  2. Perform a few searches to demonstrate the search capability.

Read a Tree Person by Person ID

If you know a person ID (PID) of someone in the Tree you can read the details of that person.

  1. Insert the following READ PID code into the tutorial.html file.
<br><br><h2>READ A TREE PERSON BY ID</h2>
<div>
  <div class="row">
    <div class="form-group col-sm-6 col-md-4">
      <label for="personIdInput">Person ID</label>
      <input type="text" class="form-control" id="personIdInput" placeholder="Person Id">
    </div>
    <p class="text-center"><button id="submit" class="btn btn-primary">Read Person ID</button></p>
  </div>
</div>

<div id="read-pid"></div>

<script> // Read tree person by ID
  var $pidContent = $('#read-pid');
  // When the user clicks on the button, get that person ID.
  $('#submit').click(function(){
    $pidContent.html('');
    var pid = $('#personIdInput').val();

    // Get the person and display the person information
    client.getPerson(pid).then(function(personResponse){
      var person = personResponse.getPerson();
      $pidContent.append('<b>Name: </b>'+person.getDisplayName()+'<br><b>Birth Date: </b>'+person.getDisplayBirthDate()+'<br><br><h1>Congratulations!</h1><br>You have completed the coding portion of the tutorial.');
    })
  
    // Catch any errors
    .catch(function(e){
      $pidContent.append(displayError(e));
    });
  
  })
</script>

  1. Save tutorial.html and refresh the browser page that is running it.
  2. Use a person ID from your search to read that person by PID.

(Proceed to Step 4 if Desired.)

⚠️ **GitHub.com Fallback** ⚠️