Query Cosmos (SQL API) from API function in Azure static web app

Phil Drew 1 Reputation point
2021-11-25T15:54:51.86+00:00

Hi, I am very new to these topic but I'm trying to make my first useful web app.

I have followed the basic "hello world" tutorial for making an Azure static web app. So I have a working website which hits a working API function, which returns "Hello from the API" and prints this to the web page. The function is in java (which I'm not very good in, but it's been a long time...). So this is all working fine. But I want my web app to do something useful, i.e. show me some items from a Cosmos DB.

I have also gone through the basic setup tutorial for a Cosmos DB (SQL API), and this includes downloading the java application, building and running it, so that Anderson/Wakefield etc. families are added to the DB. I have also made myself a new container and manually added a few items which I would like to show on the web page (I don't care about them being pretty).

I can see and follow how the code in the java app works, but how do I make something equivalent in the Static Web App function (called "message")? I have tried copying in the java app code but it fails (at least in VSCode) because it doesn't like that I want to start with the words "package" or "import" (import...= can only be used in typescript files).

This is the current code in the message function's index.js:

module.exports = async function (context, req) {
    context.res.json({
        text: "Hello from the API"
    });

What do I have to replace it with to simply grab some data from the DB and send it to the web page (select * is fine)?

I can see loads of help pages which show how the DB can be accessed from a local java app, or other places, but not from an Azure Static Web App function.

Thanks

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,006 questions
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,355 questions
Azure Static Web Apps
Azure Static Web Apps
An Azure service that provides streamlined full-stack web app development.
699 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ryan Hill 24,301 Reputation points Microsoft Employee
    2021-12-06T23:14:15.517+00:00

    Hi @Phil Drew ,

    NodeJS tutorial for the SQL API for Azure Cosmos DB is the doc you're looking for query your Cosmos DB from a NodeJS app. You'll add the SDK @azure/cosmos to your package.json. Then create a js file to handle CRUD operations. You can make this as abstract as you want to be. But to get going

       const CosmosClient = require("@azure/cosmos").CosmosClient;  
         
       const config = {  
           endpoint: "<Your Azure Cosmos account URI>",  
           key: "<Your Azure Cosmos account key>",  
           databaseId: "Tasks",  
           containerId: "Items",  
           partitionKey: { kind: "Hash", paths: ["/category"] }  
         };  
         
       /*  
       // This script ensures that the database is setup and populated correctly  
       */  
       async function create(client, databaseId, containerId) {  
           const partitionKey = config.partitionKey;  
           
           /**  
            * Create the database if it does not exist  
            */  
           const { database } = await client.databases.createIfNotExists({  
             id: databaseId  
           });  
           console.log(`Created database:\n${database.id}\n`);  
           
           /**  
            * Create the container if it does not exist  
            */  
           const { container } = await client  
             .database(databaseId)  
             .containers.createIfNotExists(  
               { id: containerId, partitionKey },  
               { offerThroughput: 400 }  
             );  
           
           console.log(`Created container:\n${container.id}\n`);  
         }  
         
       const client = new CosmosClient({config.endpoint, config.key});  
         
       const database = new client.database(config.databaseId);  
       const container = database.container(config.containerId);  
         
       // query to return all items  
       const querySpec = {  
           query: "SELECT * from c"  
         };  
           
         // read all items in the Items container  
         const { resources: items } = await container.items  
           .query(querySpec)  
           .fetchAll();  
           
         items.forEach(item => {  
           console.log(`${item.id} - ${item.description}`);  
         });  
    

    You can leverage application settings for the config object instead of hard coding the values in.

    0 comments No comments