Site icon Renzo Mischianti

DynamoDB JavaScript SDK v2 v3: add items with DB or DocumentClient – 3

Spread the love

You can use more than one method to manage items DynamoDB, some are discouraged and other can be usefully.

DynamoDB JavaScript SDK v2 v3 add items with DB or DocumentClient

Logical approach and structure are changed from v2 and v3 SDK and we are going to analyze the possibility with the 2° approach and with asynchronous and synchronous function.

Add an item

SDK v2

First we are going to create the basically asynchronous script, as we had see in the previous parts.
To execute this script go in the folder dynamodb-examples\jsv2 and launch node item_add.js

/*
 * DynamoDB Script Examples
 * Add item with DynamoDB
 * DB of selected region in AWS.config.update
 *
 * AUTHOR:  Renzo Mischianti
 *
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Renzo Mischianti www.mischianti.org All right reserved.
 *
 * You may copy, alter and reuse this code in any way you like, but please leave
 * reference to www.mischianti.org in your comments if you redistribute this code.
 */

var AWS = require("aws-sdk");

AWS.config.update({
    apiVersion: '2012-08-10',
    region: "eu-west-1",
    // endpoint: "http://localhost:8000",
    // // accessKeyId default can be used while using the downloadable version of DynamoDB.
    // // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    // accessKeyId: "9oiaf7",
    // // secretAccessKey default can be used while using the downloadable version of DynamoDB.
    // // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    // secretAccessKey: "yz5i9"
});

var ddb = new AWS.DynamoDB();

console.log("Start script!");

var params = {
    TableName: "TestTableMischianti",
    Item: {
        "ItemId": {S: "mischianti"},
        "ItemName": {S: "www.mischianti.org"},
        "ValueStr": {S: "Mischianti main url"},
        "ValueNum": {N: "1"},
    }
};


ddb.putItem(params, function (err, data) {
    if (err) {
        console.error("Unable add item", JSON.stringify(params, null, 2), ". Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("PutItem succeeded:", JSON.stringify(params, null, 2), data);
    }
});

console.log("End script!");

The console result is

D:\Projects\AlexaProjects\dynamodb-management\dynamodb-examples\jsv2>node item_add.js
Start script!
End script!
PutItem succeeded: {
  "TableName": "TestTableMischianti",
  "Item": {
    "ItemId": {
      "S": "mischianti"
    },
    "ItemName": {
      "S": "www.mischianti.org"
    },
    "ValueStr": {
      "S": "Mischianti main url"
    },
    "ValueNum": {
      "N": "1"
    }
  }
} {}

Let’s check the syntax of the parameters

var params = {
    TableName: "TestTableMischianti",
    Item: {
        "ItemId": {S: "mischianti"},
        "ItemName": {S: "www.mischianti.org"},
        "ValueStr": {S: "Mischianti main url"},
        "ValueNum": {N: "1"},
    }
};

we must specify the partition key (check the create table article), than you can add the values you need, the S or N value is the type of the data S --> String and N --> Number.

Now the asynchronous version (node item_add_async_await.js).

/*
 * DynamoDB Script Examples
 * Add item with DynamoDB async await
 * DB of selected region in AWS.config.update
 *
 * AUTHOR:  Renzo Mischianti
 *
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Renzo Mischianti www.mischianti.org All right reserved.
 *
 * You may copy, alter and reuse this code in any way you like, but please leave
 * reference to www.mischianti.org in your comments if you redistribute this code.
 *
 */

var AWS = require("aws-sdk");

AWS.config.update({
    apiVersion: '2012-08-10',
    region: "eu-west-1",
    // endpoint: "http://localhost:8000",
    // // accessKeyId default can be used while using the downloadable version of DynamoDB.
    // // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    // accessKeyId: "9oiaf7",
    // // secretAccessKey default can be used while using the downloadable version of DynamoDB.
    // // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    // secretAccessKey: "yz5i9"
});

var ddb = new AWS.DynamoDB();

(async function () {
    console.log("Start script!");

    var params = {
        TableName: "TestTableMischianti",
        Item: {
            "ItemId": {S: "mischianti"},
            "ItemName": {S: "www.mischianti.org"},
            "ValueStr": {S: "Mischianti main url"},
            "ValueNum": {N: "1"},
        }
    };

    try {
        const data = await ddb.putItem(params).promise();
        console.log("PutItem succeeded:", JSON.stringify(params, null, 2), data);
    }catch (err) {
        console.error("Unable add item", JSON.stringify(params, null, 2), ". Error JSON:", JSON.stringify(err, null, 2));
    }

    console.log("End script!");})();

As already described the difference was only the execution order.

DocumentClient

The document client abstraction makes it easier to read and write data to Amazon DynamoDB with the AWS SDK for JavaScript. Now you can use native JavaScript objects without annotating them as AttributeValue types.

Amazon

Now we are going to check the difference from DocumentClient object (node item_add_doc_client.js).

/*
 * DynamoDB Script Examples
 * Add item with DynamoDB DocumentClient
 * DB of selected region in AWS.config.update
 *
 * AUTHOR:  Renzo Mischianti
 *
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Renzo Mischianti www.mischianti.org All right reserved.
 *
 * You may copy, alter and reuse this code in any way you like, but please leave
 * reference to www.mischianti.org in your comments if you redistribute this code.
 *
 */

var AWS = require("aws-sdk");

AWS.config.update({
    apiVersion: '2012-08-10',
    region: "eu-west-1",
    // endpoint: "http://localhost:8000",
    // // accessKeyId default can be used while using the downloadable version of DynamoDB.
    // // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    // accessKeyId: "9oiaf7",
    // // secretAccessKey default can be used while using the downloadable version of DynamoDB.
    // // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    // secretAccessKey: "yz5i9"
});

var docClient = new AWS.DynamoDB.DocumentClient();

console.log("Start script!");

var params = {
    TableName: "TestTableMischianti",
    Item: {
        "ItemId": "mischianti",
        "ItemName": "www.mischianti.org",
        "ValueStr": "Mischianti main url",
        "ValueNum": 1,
    }
};

docClient.put(params, function(err, data) {
    if (err) {
        console.error("Unable add item", JSON.stringify(params, null, 2), ". Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("PutItem succeeded:", JSON.stringify(params, null, 2), data);
    }
});

console.log("End script!");

And here the console result.

D:\Projects\AlexaProjects\dynamodb-management\dynamodb-examples\jsv2>node item_add_doc_client.js
Start script!
End script!
PutItem succeeded: {
  "TableName": "TestTableMischianti",
  "Item": {
    "ItemId": "mischianti",
    "ItemName": "www.mischianti.org",
    "ValueStr": "Mischianti main url",
    "ValueNum": 1
  }
} {}

The difference is quite simple, you must look at the parameter section

var params = {
    TableName: "TestTableMischianti",
    Item: {
        "ItemId": "mischianti",
        "ItemName": "www.mischianti.org",
        "ValueStr": "Mischianti main url",
        "ValueNum": 1,
    }
};

No type is defined, the type is deduced from the data itself.

Also for this type of call you can be an synchronous call (node item_add_doc_client_async_await.js).

/*
 * DynamoDB Script Examples
 * Add item with DynamoDB DocumentClient async await
 * DB of selected region in AWS.config.update
 *
 * AUTHOR:  Renzo Mischianti
 *
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Renzo Mischianti www.mischianti.org All right reserved.
 *
 * You may copy, alter and reuse this code in any way you like, but please leave
 * reference to www.mischianti.org in your comments if you redistribute this code.
 *
 */

var AWS = require("aws-sdk");

AWS.config.update({
    apiVersion: '2012-08-10',
    region: "eu-west-1",
    // endpoint: "http://localhost:8000",
    // // accessKeyId default can be used while using the downloadable version of DynamoDB.
    // // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    // accessKeyId: "9oiaf7",
    // // secretAccessKey default can be used while using the downloadable version of DynamoDB.
    // // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    // secretAccessKey: "yz5i9"
});

var docClient = new AWS.DynamoDB.DocumentClient();

(async function () {
    console.log("Start script!");

    var params = {
        TableName: "TestTableMischianti",
        Item: {
            "ItemId": "mischianti",
            "ItemName": "www.mischianti.org",
            "ValueStr": "Mischianti main url",
            "ValueNum": 1,
        }
    };

    try {
        const data = await docClient.put(params).promise();
        console.log("PutItem succeeded:", JSON.stringify(params, null, 2), data);
    }catch (err) {
        console.error("Unable add item", JSON.stringify(params, null, 2), ". Error JSON:", JSON.stringify(err, null, 2));
    }

    console.log("End script!");
})();

The console result is the same.

D:\Projects\AlexaProjects\dynamodb-management\dynamodb-examples\jsv2>node item_add_doc_client_async_await.js
Start script!
PutItem succeeded: {
  "TableName": "TestTableMischianti",
  "Item": {
    "ItemId": "mischianti",
    "ItemName": "www.mischianti.org",
    "ValueStr": "Mischianti main url",
    "ValueNum": 1
  }
} {}
End script!

SDK v3

In v3 version there are some change and Amazon advise to use async await (synchronous) with modularization of impor. But we are going to restart from the last article syntax.

Now the asynchronous (discouraged mode) versione of the add script.

To execute this script go in the folder dynamodb-examples\jsv3 and launch node item_add.js

/*
 * DynamoDB Script Examples v3
 * Add item with DynamoDB
 * DB of selected region in configDynamoDB
 *
 * AUTHOR:  Renzo Mischianti
 *
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Renzo Mischianti www.mischianti.org All right reserved.
 *
 * You may copy, alter and reuse this code in any way you like, but please leave
 * reference to www.mischianti.org in your comments if you redistribute this code.
 *
 */

const { DynamoDBClient, PutItemCommand } = require("@aws-sdk/client-dynamodb");
const configDynamoDB = {
    version: 'latest',
    region: "eu-west-1",
    // endpoint: "http://localhost:8000",
    // credentials: {
    //     // accessKeyId default can be used while using the downloadable version of DynamoDB.
    //     // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    //     accessKeyId: "9oiaf7",
    //     // secretAccessKey default can be used while using the downloadable version of DynamoDB.
    //     // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    //     secretAccessKey: "yz5i9"
    //
    // }
};
const dbClient = new DynamoDBClient(configDynamoDB);

const addElement = (params) => {
    const command = new PutItemCommand(params);
    return dbClient.send(command);
}

console.log("Start script!");

var params = {
    TableName: "TestTableMischianti",
    Item: {
        "ItemId": {S: "mischianti"},
        "ItemName": {S: "www.mischianti.org"},
        "ValueStr": {S: "Mischianti main url"},
        "ValueNum": {N: "1"},
    }

};

const command = new PutItemCommand(params);
const data = dbClient.send(command)
    .then(
        data => console.log("PutItem succeeded:", JSON.stringify(params, null, 2), data)
    ).catch(
        err => console.error("Unable add item", JSON.stringify(params, null, 2), ". Error JSON:", JSON.stringify(err, null, 2))
    ).finally(
        () => console.log("END Of execution!")
    );

console.log("End script!");

The console output become more verbose and we have additional information.

D:\Projects\AlexaProjects\dynamodb-management\dynamodb-examples\jsv3>node item_add.js
Start script!
End script!
PutItem succeeded: {
  "TableName": "TestTableMischianti",
  "Item": {
    "ItemId": {
      "S": "mischianti"
    },
    "ItemName": {
      "S": "www.mischianti.org"
    },
    "ValueStr": {
      "S": "Mischianti main url"
    },
    "ValueNum": {
      "N": "1"
    }
  }
} { '$metadata':
   { httpStatusCode: 200,
     httpHeaders:
      { server: 'Server',
        date: 'Fri, 15 Jan 2021 21:38:39 GMT',
        'content-type': 'application/x-amz-json-1.0',
        'content-length': '2',
        connection: 'keep-alive',
        'x-amzn-requestid': '035UKDLIR2FGUQ66ISB3UG8K17VV4KQNSO5AEMVJF66Q9ASUAAJG',
        'x-amz-crc32': '2745614147' },
     requestId: '035UKDLIR2FGUQ66ISB3UG8K17VV4KQNSO5AEMVJF66Q9ASUAAJG',
     attempts: 1,
     totalRetryDelay: 0 },
  Attributes: undefined,
  ConsumedCapacity: undefined,
  ItemCollectionMetrics: undefined }
END Of execution!

In detail we have l’http status code to identify the status of response (httpStatusCode: 200), and for the developer it is now explicit that we work with REST calls.

If you want you can import directly all the package (discouraged) so you return to the v2 modality in term of package management, here the example.

node item_add_all_package.js

/*
 * DynamoDB Script Examples v3
 * Add item with DynamoDB Import main package instead single module
 * DB of selected region in configDynamoDB
 *
 * AUTHOR:  Renzo Mischianti
 *
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Renzo Mischianti www.mischianti.org All right reserved.
 *
 * You may copy, alter and reuse this code in any way you like, but please leave
 * reference to www.mischianti.org in your comments if you redistribute this code.
 */

const CDDB = require("@aws-sdk/client-dynamodb");
const configDynamoDB = {
    version: 'latest',
    region: "eu-west-1",
    // endpoint: "http://localhost:8000",
    // credentials: {
    //     // accessKeyId default can be used while using the downloadable version of DynamoDB.
    //     // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    //     accessKeyId: "9oiaf7",
    //     // secretAccessKey default can be used while using the downloadable version of DynamoDB.
    //     // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    //     secretAccessKey: "yz5i9"
    //
    // }
};
const dbClient = new CDDB.DynamoDBClient(configDynamoDB);

const addElement = (params) => {
    const command = new PutItemCommand(params);
    return dbClient.send(command);
}

console.log("Start script!");

var params = {
    TableName: "TestTableMischianti",
    Item: {
        "ItemId": {S: "mischianti"},
        "ItemName": {S: "www.mischianti.org"},
        "ValueStr": {S: "Mischianti main url"},
        "ValueNum": {N: "1"},
    }

};

const command = new CDDB.PutItemCommand(params);
const data = dbClient.send(command)
    .then(
        data => console.log("PutItem succeeded:", JSON.stringify(params, null, 2), data)
    ).catch(
        err => console.error("Unable add item", JSON.stringify(params, null, 2), ". Error JSON:", JSON.stringify(err, null, 2))
    ).finally(
        () => console.log("END Of execution!")
    );

console.log("End script!");

Naturally you don’t do that, but It isn’t prohibited.

Now the synchronous script (node item_add_async_await.js)

/*
 * DynamoDB Script Examples v3
 * Add item with DynamoDB async await
 * DB of selected region in configDynamoDB
 *
 * AUTHOR:  Renzo Mischianti
 *
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Renzo Mischianti www.mischianti.org All right reserved.
 *
 * You may copy, alter and reuse this code in any way you like, but please leave
 * reference to www.mischianti.org in your comments if you redistribute this code.
 *
 */

const { DynamoDBClient, PutItemCommand } = require("@aws-sdk/client-dynamodb");
const configDynamoDB = {
    version: 'latest',
    region: "eu-west-1",
    // endpoint: "http://localhost:8000",
    // credentials: {
    //     // accessKeyId default can be used while using the downloadable version of DynamoDB.
    //     // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    //     accessKeyId: "9oiaf7",
    //     // secretAccessKey default can be used while using the downloadable version of DynamoDB.
    //     // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    //     secretAccessKey: "yz5i9"
    //
    // }
};

const dbClient = new DynamoDBClient(configDynamoDB);

(async function () {
    console.log("Start script!");

    var params = {
        TableName: "TestTableMischianti",
        Item: {
            "ItemId": {S: "mischianti"},
            "ItemName": {S: "www.mischianti.org"},
            "ValueStr": {S: "Mischianti main url"},
            "ValueNum": {N: "1"},
        }
    };

    try {
        const command = new PutItemCommand(params);
        const data = await dbClient.send(command);
        console.log("PutItem succeeded:", JSON.stringify(params, null, 2), data);
    } catch (err) {
        console.error("Unable add item", JSON.stringify(params, null, 2), ". Error JSON:", JSON.stringify(err, null, 2));
    }

    console.log("End script!");
})();

You can also prevent tedious creation of command then call It with send command, the package DynamoDB have all the command inside with implicit declaration of the commands object.

const ddb = new DynamoDB(configDynamoDB);
[...]
const data = await ddb.putItem(params);

But this approach is discouraged because reduce the modularization, all the command declaration are imported, and package size grow.

But here an example with this method.

/*
 * DynamoDB Script Examples v3
 * Add item with DynamoDB async await with
 * implicit command declaration
 * DB of selected region in configDynamoDB
 *
 * AUTHOR:  Renzo Mischianti
 *
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Renzo Mischianti www.mischianti.org All right reserved.
 *
 * You may copy, alter and reuse this code in any way you like, but please leave
 * reference to www.mischianti.org in your comments if you redistribute this code.
 *
 */

const { DynamoDB } = require("@aws-sdk/client-dynamodb");
const configDynamoDB = {
    version: 'latest',
    region: "eu-west-1",
    // endpoint: "http://localhost:8000",
    // credentials: {
    //     // accessKeyId default can be used while using the downloadable version of DynamoDB.
    //     // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    //     accessKeyId: "9oiaf7",
    //     // secretAccessKey default can be used while using the downloadable version of DynamoDB.
    //     // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
    //     secretAccessKey: "yz5i9"
    //
    // }
};

const ddb = new DynamoDB(configDynamoDB);

(async function () {
    console.log("Start script!");

    var params = {
        TableName: "TestTableMischianti",
        Item: {
            "ItemId": {S: "mischianti"},
            "ItemName": {S: "www.mischianti.org"},
            "ValueStr": {S: "Mischianti main url"},
            "ValueNum": {N: "1"},
        }
    };

    try {
        const data = await ddb.putItem(params);
        console.log("PutItem succeeded:", JSON.stringify(params, null, 2), data);
    } catch (err) {
        console.error("Unable add item", JSON.stringify(params, null, 2), ". Error JSON:", JSON.stringify(err, null, 2));
    }

    console.log("End script!");
})();

Check the data

  1. You can find all the data in the DynamoDB section of the AWS console, go to this link (check the region).
https://eu-west-1.console.aws.amazon.com/dynamodb/home?region=eu-west-1#
  1. Click on Table/Tabelle;
  2. Select TestTableMischianti table;
  3. Click on element tab.
DynamoDB Table items from AWS console

Thanks

  1. DynamoDB JavaScript SDK v2 v3: prerequisite and SDK v2 v3 introduction
  2. DynamoDB JavaScript SDK v2 v3: manage tables
  3. DynamoDB JavaScript SDK v2 v3: add items with DB or DocumentClient
  4. DynamoDB JavaScript SDK v2 v3: manage items
  5. DynamoDB JavaScript SDK v2 v3: scan table data and pagination
  6. DynamoDB JavaScript SDK v2 v3: query

Spread the love
Exit mobile version