Implement the IDataService interface


You have to implement the interface IDataService, and add a function to initialise your provider (with the parameters you need)
  • add: function to add entity, it take as arguments tablename, entity and two callback (success and error)

  • update : function to update entity, it take as arguments tablename, entity and two callback (success and error)

  • remove: function to remove entity, it take as arguments tablename, entity and two callback (success and error)

  • get: function to get tables rows, it take as arguments a Callback and an array of last Sync Dates.

    The callback is called with an array of objects { tableName: , table: }


                
declare module CloudDataConnector {
    interface IDataService {
        _dataId: number;
        tableNames: string[];
        add(tableName: string, entity: any, onsuccess: (newEntity: any) => void, onerror: (error: string) => void): void;
        update(tableName: string, entity: any, onsuccess: (newEntity: any) => void, onerror: (error: string) => void): void;
        get(updateCallback: (result: any) => void, lastSyncDates: {
            [x: string]: Date;
        }): void;
        remove(tableName: string, entity: any, onsuccess: () => void, onerror: (error: string) => void): void;
    }
}
                            
                            

Amazon Web Services


Set up AWS Services


We will run through the process of setting up a backend with A.W.S. It will enable you to run the samples and play with AngularCDC.

Create an Amazon Web Services account


You will first need an AWS account. If you don't already have one, you could register for a free trial.


Configure your backend


Once you have your account, we will need to get your AccountId, create a Role, set permissions and create an identity pool.


AccountId

Click here to get your accountId




Role

Create a new role : click here



Set a friendly name, the role type = "Amazon EC2 Role for Data Pipeline ", replace the Policy Document by the following parameters and validate.

                    
  {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [       
        "dynamodb:Scan",
        "dynamodb:Query",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:DeleteItem", 
        "dynamodb:UpdateItem",
        "dynamodb:BatchGetItem",
        "dynamodb:UpdateTable"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}
                                      
                                

Identity Pool


Create your new Identity Pool here




Set a friendly name, check the "Enable Access to Unauthenticated Identities" option click on create pool, in "Assign Role to Unauthenticated Identities" section, choose the role that you just created and click on update roles. Finaly click on done button. Click on "Edit Identity Pool" to get the Identity Pool ID




Go back to the roles List , select the new role, get the "Role ARN" and edit the trust Relationships (replace the Policy Document by the following parameters where "us-east-1:d0023d8a-3369-4d1a-9f3e-a5f5c0dabbce" is your Identity Pool ID and click on update)


                
 {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "us-east-1:d0023d8a-3369-4d1a-9f3e-a5f5c0dabbce"
        }
      }
    }
  ]
}                                     
                                
                            

Create your DynamoDB


In this page, you can create a new dynamo db.

Choose a friendly name, we choose "people", set primary key type as hash and "id" as Hash Attribute Name.


Implement provider


init Source

This function is called to initialise the AWS


                AWSDataService.prototype.initSource = function (AccountId, RoleArn, idPool, region, tableNames) {
            AWS.config.region = region;
            AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                AccountId: AccountId,
                IdentityPoolId: idPool,
                RoleArn: RoleArn
            });
            AWS.config.credentials.get(function (credentialsResults) {
            });
            this.AWSClient = new AWS.DynamoDB();
            this.tableNames = tableNames;
};
                            
                            

add

This function is called to add an entity


                
AWSDataService.prototype.add = function (tableName, entity, onsuccess, onerror) {
    var dynDB = new AWS.DynamoDB();
    delete entity.$$hashKey;
    entity.id = Math.random() + '';
    // create the item with the correct mapping for DynamoDB
    var item = {};
    for (var i in entity) {
        if (typeof (entity[i]) != 'function')
            item[i] = { "S": entity[i] };
    }
    dynDB.putItem({
        'TableName': tableName,
        "Item": item,
        "Expected": {},
        }, onsuccess, onerror);
};



update

This function is called to update an entity


                
AWSDataService.prototype.update = function (tableName, entity, onsuccess, onerror) {
    var dynDB = new AWS.DynamoDB();
    // create the item with the correct mapping for DynamoDB
    var item = {};
    for (var i in entity) {
    if (typeof (entity[i]) != 'function' && i != 'id')
        item[i] = { "Value": { "S": entity[i] }, "Action": "PUT" };
    }
    dynDB.updateItem({
        'TableName': tableName,
        "Key": { "id": { "S": entity.id } },
        "AttributeUpdates": item,
        "Expected": {},
    }, function (e) { }, onerror);
};



remove

This function is called to remove an entity


                
AWSDataService.prototype.remove = function (tableName, entity, onsuccess, onerror) {
    var dynDB = new AWS.DynamoDB();
    this.deletedItem = entity;
    this.deletedItem.sync_deleted = true;
    dynDB.deleteItem({
        "TableName": tableName,
        "Key": { "id": { "S": entity.id + "" } },
        "ReturnValues": "ALL_OLD"
    }, onsuccess, onerror);
};



get

This function is called to get tables rows, it take as arguments a Callback and an array of last Sync Dates. The callback is called with an array of objects { tableName: , table: }


 
                
AWSDataService.prototype.get = function (updateCallback, lastSyncDates) {
    this.dataAvailableCallback = updateCallback;
    var count = 0;
    var total = this.tableNames.length;
    var result = [];
    var tableName;
    for (var x = 0; x < total; x++) {
        tableName = this.tableNames[x];
        var lastSyncDate = lastSyncDates[tableName];
        this._getTable(tableName, function (resultElement) {
            count++;
            updateCallback([resultElement]);
            if (count == total) {
            }
        }, lastSyncDate);
    }
};
AWSDataService.prototype._getTable = function (tableName, callback, lastDate) {
    var Table = new AWS.DynamoDB({ params: { TableName: tableName } });
    var firstCall = false;
    if (!lastDate) {
        lastDate = new Date(null);
        firstCall = true;
    }
    var that = this;
    // Since the server sets the updateData and we are doing a sort on date we assume we will never miss an item as long as we query from our latest update date.
    this.AWSClient.scan({ TableName: tableName }, function (err, table) {
        if (err) {
            console.log(err);
            callback(null);
        }
        else {
            var items = [];
            for (var i = 0; i < table.Items.length; i++) {
                // create the item with the correct mapping for DynamoDB   
                var item = {}
                for (var x in table.Items[i]) {
                item[x] = table.Items[i][x].S;
            }
            items.push(item);
        }
        if (that.deletedItem)
            items.push(that.deletedItem);
        var result = { 'tableName': tableName, 'table': items };
        callback(result);
        that.deletedItem = null;
        }
    });
};


Create your JS application


Now it's time to create your JS application. First create a html file, say "index.html", and fill it with a blank html structure like this:


<html>
    <head></head>
    <body></body>
</html>
                    

Reference libraries

Add the references to the Cloud Data Connector available on CDN: http://az633345.vo.msecnd.net/cdn/ajax/acdc/0.95/angular-cdc.js js file and the Amazon provider API in the head of your page, as well as a reference to the Amazon Web Services client library.


<script src="[path]/cdc.js"></script>
<script src="[path]/angular-cdc-amazonwebservices.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.0.min.js"></script>

Add the reference to the angular CDC module (if you are using Angular)


<script src="[path]/angularModule.js"></script>

Declare your app

In your index.html, add a script tag after the references, and declare your application module.


<script type="text/javascript">
  $(function(){
    var app = angular.module('demoApp', ['AngularCDC', 'AngularCDC.AWS']);
  });
</script>

Now you could use your application module to bootstrap the application.

<html ng-app="demoApp">

Create Angular controller

To add some UI, you will add a controller, just after the creation of the module.

app.controller('demoController', ['$scope', 'CDCService', 'angularCDCAWS', function ($scope, CDCService, angularCDCAWS) {
    }
]);

The controller declares dependencies on dataService, your Cloud Data Connector, and amazonDataService, your provider for Amazon Web Services.

Call your controller in your index.html

Now you have to link your controller to something. Add this declaration on the body node :

<body ng-controller="demoController">

Link your app to A.W.S. and connect

The A.W.S. provider must be configured to work properly. You will initialize it and specify your data source and the tables you want to use. You will also register the A.M.S. provider in AngularCDC.


$scope.initialize = function () {
// configure A.W.S.
    $scope.initialize = function () {
        //angularCDCAWS.initSource('AccountId','Role ARN','Identity Pool ID','region', ['dynamoDbName'])
        angularCDCAWS.initSource('659273569624', 'arn:aws:iam::659273569624:role/acdc', 'us-east-1:c8a135e8-8b1a-4f1b-88ff-08d72bc8389b', 'us-east-1', ['people']);
        CDCService.addSource(angularCDCAWS);
        CDCService.connect(function (results) {
            // We are good to go
        }, $scope, 3);
    };
};
$scope.initialize();

Amazon Cloud Data Connector requires your AccountId, Role ARN, Identity Pool ID, region and your table name.

Amazon Cloud Data Connector will create a data source and you will work with AmazonDataService to Add, Edit, Update and Delete your stuff.


Let there be Rock !


You can now get the most out of CDC and add, edit, update and delete stuff to/from your AWS backend.


// function to add a new data entry
$scope.Add = function (tableName, entity) {
                    CDCService.add(tableName, entity);
                    CDCService.commit(function () {
                    }, function () {
                        console.log('Problem adding data');
                    });
                    $scope.menu = "main";
                    $scope.currentEdit = {};
                };

$scope.Change = function (tableName, entity) {
                    // entity is already controlled, we just need to call a commit
                    CDCService.commit(function () {
                    }, function (err) {
                        console.log('Problem updating data: ' + err.message);
                    });
                    $scope.menu = "main";
                    $scope.currentEdit = {};
                };
                        

 $scope.Delete = function (tableName, entity) {
                    CDCService.remove(tableName, entity);
                    CDCService.commit(function () {
                    }, function (err) {
                        console.log('Problem deleting data: ' + err.message);
                    });
                    $scope.menu = "main";
                    $scope.currentEdit = {};
                };
                        
// function to sync the data
$scope.sync = function () {
    CDCService.readAll();
};