0
votes

I am new to Typescript and CosmosDB, this might be a fairly stupid question, however, I am searched around online for the whole day and could not find the solution works fine for my case. Hope someone would willing to help here.

Basically I was trying to implement RESTful APIs with Azure function(javascript/typescript), what exactly the APIs do is connecting to and querying from my Azure cosmosdb(sql). Data binding was what I used to bind the database with my functions. The thing is I am not sure how to select value from the db according to specific column value(select id from table where username="abc").

To make my question clearer, here is my user item in cosmos db:

{
    "id": "1",
    "userid": "33218898",
    "username": "test1",
    "password": "psw",
    "email": "[email protected]",
    "momentID": [
        "1",
        "2",
        "3"
    ],
    "followingID": [
        "2",
        "3"
    ],
    "followerID": [
        "2",
        "3"
    ]
}

This is how I got the users from the azure function:

module.exports = async function (context, req, inputDocument) {
    context.log('JavaScript HTTP trigger function processed a request.');
    if (!!inputDocument && inputDocument.length > 0) {
            if(req.query.id || (req.body && req.body.id)){
                context.res = {
                    // status: 200, /* Defaults to 200 */
                    body: "User with id [" + req.query.id + "] is :" + inputDocument[req.query.id-1].username
                };
            }
            else if(req.query.name || (req.body && req.body.name)){
                const user = inputDocument.select("[@username='test1_update']");
                const userid = user.id;
                context.log('User id with username :' , userid);
            }else{
                var arr_user = new Array(inputDocument.length);

                for(var _i = 0; _i <inputDocument.length; _i++)
                {
                    arr_user[_i] = inputDocument[_i].username;
                }
                context.res = {
                    status: 200, 
                    body: "Hello " + arr_user
                };
                context.log('Username: ', arr_user);
            }
    }  
    else{
        context.log('Nothing in the inputDocument');
    }
};

It seems select is not a defined function in typescript, could anyone kindly help with this?

1

1 Answers

-1
votes

You can use @azure/cosmos package with javascript to read the data from the collection.

const CosmosClient = require("@azure/cosmos").CosmosClient;

getUser: async function (login) {
    const querySpec = {
      query: 'SELECT * FROM users',
      parameters: [
      ]
    };

    const result = await cosmosClient
      .database(databaseId)
      .container(containerId)
      .items.query(querySpec)
      .fetchNext();

    if (result && result.resources) {
      return result.resources[0];
    }

    return undefined;
  }

Here is a sample