简体   繁体   中英

How to use node.js generators with DynamoDB

I am trying to use generators to put and get data from my local dynamoDB. My code, so far, returns quite large objects. But I'm not quite sure if I actually interact with the database. And if so, I can't figure out how to actually retrieve data. Another thing is the callback function which is needed when not using generators. Am I supposed to leave it out? If not, how would I yield the result to the next()-function?

Any help is deeply appreciated! :-)

So far my code looks like this:

'use strict';

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

AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});
AWS.config.update({region: 'us-west-1'});
AWS.config.apiVersion = '2015-10-01';
//Using DynamoDB Local
var dyn = new AWS.DynamoDB({ endpoint: new AWS.Endpoint('http://localhost:8000') });

//Wrap the async calls in a generator functions
function* putItemGenerator(putParams) {
    yield dyn.putItem(putParams);
}
function* getItemGenerator(getParams) {
    yield dyn.getItem(getParams);
}

class User {
    //The constructor creates a new user in the 
    //database and inserts his ID and name
    constructor (args) {
        this.userId = args.userId;
        this.name = args.name;

        let putParams = {
            "TableName": "Users",
            "Item": {
                userId: { S: this.userId },
                name: { S: this.name }
            }
        };

        //Greate a generator and run it.
        let result = putItemGenerator(dyn, putParams).next();

        console.log(" === PUT RESULT === ");
        console.log(result.value);
    }

    //Get the User from the Database
    getUser() {
        var getParams = {
            "TableName": "Users",
            "ConsistentRead": true,
            "Key": {
                "userId": { S: this.userId },
            }
        };

        let result = getItemGenerator(dyn, getParams).next();

        console.log(" === GET RESULT === ");
        console.log(result.value);

        return result.value;
    }
}

var user = new User( {
    userId: "1337",
    name: "John Doe"
} );

user.getUser();

/*
//I created the table with this script.

'use strict';

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

var createTables = function() {
    AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});
    AWS.config.update({region: 'us-west-1'});
    AWS.config.apiVersion = '2015-10-01';
    let dyn = new AWS.DynamoDB({ endpoint: new AWS.Endpoint('http://localhost:8000') });

    params = {
        TableName : "Users",
        KeySchema: [
            { AttributeName: "userId", KeyType: "HASH" }
        ],
        AttributeDefinitions: [  
            { AttributeName: "userId", AttributeType: "S" }
        ],
        ProvisionedThroughput: {       
            ReadCapacityUnits: 1, 
            WriteCapacityUnits: 1
        }
    };
    dyn.createTable(params, function(err, data) {
        if (err)
            console.log(JSON.stringify(err, null, 2));
        else
            console.log(JSON.stringify(data, null, 2));
    });
}

createTables();
*/

I found out that what I want to do is not possible. A getter that retrieves it's value by an I/O operation can not return a value. A best practice would be to return a so called promise. This can be used by the calling function as soon as the value is available. Generators can make the code look more beautiful and easy to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM