# Azure Storage JavaScript Client Library Sample for Table Operations

In this sample, we will demonstrate common scenarios for Azure Table Storage that includes creating, listing and deleting tables and entities.

Azure Storage table is a service that stores structured NoSQL data in the cloud. Table storage is a key/attribute store with a schemaless design. Because Table storage is schemaless, it's easy to adapt your data as the needs of your application evolve. Access to data is fast and cost-effective for all kinds of applications. Table storage is typically significantly lower in cost than traditional SQL for similar volumes of data.

Note: You may need set up a HTTP server to host this sample for IE11 and latest Chrome.

## Contents:

- Step 1: Preparing an Azure Storage account with CORS rules set
- Step 2: Importing Azure Storage JavaScript Client Library
- Step 3: Creating an Azure Storage Table Service Object
- Step 4: Table Operations
- Step 5: Table Entities Operations
- Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library

## Step 1: Preparing an Azure Storage account with CORS rules set

Cross-origin resource sharing, or CORS, must be configured on the Azure Storage account to be accessed directly from JavaScript in the browser. You are able to set the CORS rules for specific Azure Storage account on the Azure Portal. The "Allowed origins" could be set to "*" to allow all the origins in this sample. For more information about CORS, see Cross-Origin Resource Sharing (CORS).

## Step 2: Importing Azure Storage JavaScript Client Library

Importing `azure-storage.table.js` in your HTML file for table operations.

    <script src="azure-storage.table.js"></script>

## Step 3: Creating an Azure Storage Table Service Object

The `TableService` object lets you work with table and entities. Following code creates a `TableService` object with storage account and SAS Token.

    var tableUri = 'https://' + 'STORAGE_ACCOUNT' + '.table.core.windows.net';
    var tableService = AzureStorage.Table.createTableServiceWithSas(tableUri, 'SAS_TOKEN');

You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable `AzureStorage.Table` will be set, which is the start point where we can create service objects for table and access to the storage utilities.

How to get full detailed API definitions? Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs. Please check API details on Azure Storage API reference documents. The JavaScript global variable `AzureStorage.Table` is just like the object `require('azure-storage')` returns in Node.js, but limits to Table related interfaces. Go to TableService to view possible methods provided by `TableService` class.
Warning: Azure Storage JavaScript Client Library also supports creating `TableService` based on Storage Account Key for authentication besides SAS Token. However, for security concerns, we recommend use of a limited time SAS Token, generated by a backend web server using a Stored Access Policy.

## Step 4: Table Operations

Table: A table is a collection of entities. Tables don't enforce a schema on entities, which means a single table can contain entities that have different sets of properties. The number of tables that a storage account can contain is limited only by the storage account capacity limit.

### List Tables

`TableService` provides `listTablesSegmented` and `listTablesSegmentedWithPrefix` for retrieving the table list under your storage account.

    tableService.listTablesSegmented(null, {maxResults : 200}, function (error, results) {
        if (error) {
            // List tables error
        } else {
            for (var i = 0, table; table = results.entries[i]; i++) {
                // Deal with table object
            }
        }
    });

### Create Table

`TableService` provides `createTable` and `createTableIfNotExists` for creating a table under a storage account.

    tableService.createTableIfNotExists('mytable', function(error, result) {
        if (error) {
            // Create table error
        } else {
            // Create table successfully
        }
    });

### Delete Table

`TableService` provides `deleteTable` and `deleteTableIfExists` for deleting a table under a storage account.

    tableService.deleteTableIfExists('mytable', function(error, result) {
        if (error) {
            // Delete table error
        } else {
            // Delete table successfully
        }
    });

### Executable Example

The sample will try to create an Azure Storage table service object based on SAS Token authorization. Enter your Azure Storage account name and SAS Token here. Make sure you have set the CORS rules for the Azure Storage table service, and the SAS Token is in valid period.

Storage account: SAS Token:

Azure Storage table service provides plenty of interfaces for table operations. In following example, you can try to list all the tables under your storage account, and try to create or delete one table from your account.

- Click
  button to view the table list under your Azure Storage account

- Click
  button to create a table under your Azure Storage account

  New Table Name:

- Click "Delete" button to delete the table under your Azure Storage account

- Click "Select" button to operate with the table entities in next step

## Step 5: Table Entities Operations

Entity: An entity is a set of properties, similar to a database row. An entity can be up to 1MB in size.

Properties: A property is a name-value pair. Each entity can include up to 252 properties to store data. Each entity also has 3 system properties that specify a partition key, a row key, and a timestamp. Entities with the same partition key can be queried more quickly, and inserted/updated in atomic operations. An entity's row key is its unique identifier within a partition.

### Query Entities

`TableService` provides `queryEntities` for querying a table under a storage account.

    var tableQuery = new AzureStorage.Table.TableQuery().top(200);
    tableService.queryEntities('mytable', tableQuery, null, function(error, result) {
        if (error) {
            // Query entities error
        } else {
            for (var i = 0, entity; entity = results.entries[i]; i++) {
                // Deal with entity object
            }
        }
    });

### Insert or Replace Entity

`TableService` provides `insertEntity`, `insertOrReplaceEntity` and `insertOrMergeEntity` for adding a table entity under a storage account.

    var insertEntity = {
        PartitionKey: {'_': 'partitionKey'},
        RowKey: {'_': 'rowKey'}
    };

    tableService.insertOrReplaceEntity('mytable', insertEntity, function(error, result, response) {
        if(error) {
            // Insert table entity error
        } else {
            // Insert table entity successfully
        }
    });

### Delete Entity

`TableService` provides `deleteEntity` for deleting a table entity under a storage account.

    var deleteEntity = {
        PartitionKey: {'_': 'partitionKey'},
        RowKey: {'_': 'rowKey'}
    };

    tableService.deleteEntity('mytable', deleteEntity, function(error, result, response) {
        if(error) {
            // Delete table entity error
        } else {
            // Delete table entity successfully
        }
    });

### Executable Example

After clicked the "Select" button on the table list, you are able to operate with the table entities under the selected table.

- Click
  button to refresh the entity list in your selected table

- Click
  button to create an entity in your selected table. If existing entity with the sampe PartitionKey and RowKey, old entity will be merged.

  PK RK CustomProperty1 CustomProperty2

- Click "Delete" button to delete the selected table entity in your selected table

### Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library

1. Setting CORS rules for your selected Azure-Storage account table service.
2. Including functional file(s) needed, such as "azure-storage.table.js" for table operation.
3. Using keyword "AzureStorage.Table" to access to Azure storage JavaScript APIs for tables.
4. Referring to API documents for detailed API definitions.

You can view the source code of this sample for detailed reference.