0

Use case: I am trying to insert a record inside the amazon QLDB using Node and typescript. I am able to insert the record/document successfully and it returns me documentID in return.

there are 2 controllers: EntityController and CommonController -EntityController extends CommonController -EntityController has the code for getting req object converting it into the model object and the calling insert() function that has been extended from the CommonController.

problem I am trying to propagate that documentID to all the way to my API call, but somehow I am getting undefined in the EntityController. whereas I am able to print the documentID in CommonController.

I am not sure why I am getting undefined when I am clearly returning a value.

const CommonController = require("../template/controller");
import { Request, Response } from 'express';
const tableName:string = "entities";
const EntityModel = require("./model")

class EntityController extends CommonController {
    async insertEntitiy(req:Request,res:Response) {
    async insertEntitiy(req:any,res:any) {
        console.log(req);
        console.log("===========");
        console.log(req.body);
        let entity = new EntityModel();
        entity.balance = req.body.balance;
        entity.firstName = req.body.firstName;
        entity.lastName = req.body.lastName;
        entity.email = req.body.email;
        try {
            let documentIds = await this.insert(tableName,entity);
            console.log("--------- inside insertEntity fiunction()---------");
            console.log(documentIds);
            console.log("------------------");
            res.status(200).send(documentIds[0]);
        } catch (error) {
            console.error(`error in creating Entity: ${error}`);
            res.status(500).send({ errMsg: `error in creating Entity: ${error}` });
        }
    } 
}

module.exports = new EntityController();



import { createQldbWriter, QldbSession, QldbWriter, Result, TransactionExecutor } from "amazon-qldb-driver-nodejs";
import { Reader } from "ion-js";
import { error, log } from "../qldb/LogUtil";
import { getFieldValue, writeValueAsIon } from "../qldb/Util";
import { closeQldbSession, createQldbSession } from "../qldb/ConnectToLedger";

module.exports = class Conroller {
  async insert(tablename:string, object:any): Promise<Array<string>> {
    let session: QldbSession;
    let result:Array<string>;
    try {
        session = await createQldbSession();
        await session.executeLambda(async (txn) => {
            result =  await this.insertDocument(txn,tablename,object);
            console.log("---------result inside insert fiunction()---------");
            console.log(result);
            console.log("------------------");
            return (Promise.resolve(result));
          })
    } catch (e) {
        error(`Unable to insert documents: ${e}`);
        return(["Error"]);
    } finally {
        closeQldbSession(session);
    }
  }

  /**
  * Insert the given list of documents into a table in a single transaction.
  * @param txn The {@linkcode TransactionExecutor} for lambda execute.
  * @param tableName Name of the table to insert documents into.
  * @param documents List of documents to insert.
  * @returns Promise which fulfills with a {@linkcode Result} object.
  */
  async  insertDocument(
    txn: TransactionExecutor,
    tableName: string,
    documents: object
  ): Promise<Array<string>> {
    const statement: string = `INSERT INTO ${tableName} ?`;
    const documentsWriter: QldbWriter = createQldbWriter();
    let documentIds: Array<string> = [];
    writeValueAsIon(documents, documentsWriter);
    let result: Result = await txn.executeInline(statement, [documentsWriter]);
    const listOfDocumentIds: Reader[] = result.getResultList();
    listOfDocumentIds.forEach((reader: Reader, i: number) => {
      documentIds.push(getFieldValue(reader, ["documentId"]));   
    });
    console.log("---------documentIds---------");
    console.log(documentIds);
    console.log("------------------");
    return (documentIds);
  }
}

ouptut : ---------documentIds---------

[ '4o5UZjMqEdgENqbP9l7Uhz' ]

---------result inside insert fiunction()---------

[ '4o5UZjMqEdgENqbP9l7Uhz' ]

--------- inside insertEntity fiunction()---------

undefined

  • 2
    It doesn't look like you are returning anything in your `insert` method except in the catch. Should you be having the following? `return await session.executeLambda(...)` – Daniel W Strimpel Feb 06 '20 at 16:37

1 Answers1

1

As @daniel-w-strimpel pointed out in the comments, your insert method returns only in the catch part.

Try this:

insert(tablename:string, object:any): Promise<Array<string>> {
  let session: QldbSession;
  let result: Array<string>;
  try {
    session = await createQldbSession();
    return session.executeLambda(async (txn) => {
      result = await this.insertDocument(txn,tablename,object);
      console.log("---------result inside insert fiunction()---------");
      console.log(result);
      console.log("------------------");
      return result;
    })
  } catch (e) {
    error(`Unable to insert documents: ${e}`);
    return(["Error"]);
  } finally {
    closeQldbSession(session);
  }
}
...

In return session.executeLambda you return the Promise.

In return result; you return the actual value.

More on promises here: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

niccord
  • 764
  • 4
  • 20