Create an Angular todo list with azure static web apps Part 4

In this series about Azure static web apps, we created an Angular Todo list app, an Azure function using JavaScript and linked both together. If you want to have a look at the previous parts, here are the links

In this post, we will store the todos in Cosmos DB and read it from our Azure function.

Create Cosmos DB

Azure Cosmos DB gives you a free account with upto 400 RU/s. You can use it for this demo. Go to Azure Portal, Click New Resource -> Under Databases select Azure Cosmos DB, choose the API as SQL API and add the account name, resource group and region and leave everything else with the default value then click Review + Create then Create.

Once the Azure Cosmos DB account is created, open it and go to Data Explorer and from the toolbar click New Database and give it a name

Once the database is created, click the three dots near the database name and click New Container. Provide a name for the container and type /id as the partition key then click ok

From the left menu click Keys and copy the PRIMARY CONNECTION STRING.

Azure Function Settings

To connect to the Azure Cosmos DB, we we will need to store the connection string somewhere. For this purpose, we will use the file local.settings.json under api folder.

Add a new key under the values key and name it CosmosConnectionString and paste the Cosmos DB connection string copied earlier.

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "CosmosConnectionString":""
  },"Host": {
    "CORS": "*"
  }
}

The local.settings.json file is not added to Git and should not be. This should include the connection strings and any secrets used locally.

Connect to Cosmos from the APIs

We have the database ready now and the connection string is set in our api. To read data from Cosmos, we need to install the package @azure/cosmos. Open command prompt and navigate to the api folder that has the function project and run the following command

npm i @azure/cosmos

Now open the index.js file inside the api/GetTodoList folder and paste the following code

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

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    let cosmosClient = new CosmosClient(process.env['CosmosConnectionString']);
    let database = cosmosClient.database('todos');
    let container = database.container('todolist');
    let {resources} = (await container.items.query('SELECT c.id,c.title,c.isCompleted FROM c').fetchAll());

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: resources
    };
}

The code is straight forward, in line 1, we imported the CosmosClient class which will be used to connect to Cosmos DB. This is like an EntityFramework DBContext. Line 5,6, and 7 we create a client instance, use it to get a reference to the database and the container that has our data.

In line 8, we query the container to return only the id, title and isCompleted fields and return the results.

You can see that the field names are now pascal named (title instead of Title), you will have to update the binding in the TodoList component

 <td><input type="checkbox" [checked]="todo.isCompleted" disabled></td>

Test

Run your api project with func start and your Angular app with ng serve. You should see an empty list. Go back to your Cosmos DB instance in Azure Portal, click Data Explorer, select the db then the container and choose Items. You can add a new item by clicking the New Item button on the toolbar and then click Save. Repeat the process to add few items

Now try to refresh your app and you should see the data displayed in the Angular app

Deployment

Commit and push your changes and wait for the workflow action to finish. If you tried your site now it will not work as the function has no idea about the connection string. To add a new connection string, open your Azure Static Web App, click on Configuration and then click Add. Type CosmosConnectionString as the name and paste the connection string for the Cosmos DB in the value field. Save and refresh your app and now you should see the application displaying the data you saved in Cosmos DB

Source code: https://github.com/haitham-shaddad/ng-todo-list-az-static-webapp

Create an Angular todo list with azure static web apps Part 1

In this post, I will create a To Do List app using Angular and we will host it on the newly introduced Azure service called Static Web Apps.

Project Setup

Azure static web app is connected to GitHub repo, and the first thing to do is to create a new repo under your github account. Once you create it, clone it to your local machine and run the following commands. Make sure you have angular-cli tools installed

ng new AzTodoList

Choose yes for routing and select your preferred css processor and hit enter to create the project and install all needed packages. Once all packages are installed, run ng serve to make sure the app works fine. You should have something like this running on port 4200

Make sure all files exist in the root folder where you cloned the GitHub repo. If you cloned the repo in a folder called ToDoList and then ran the command ng new inside it, it will create another subfolder. If this happened, make sure to move the files in the inner folder to the ToDoList folder. Otherwise, the GitHub action won’t work since it will fail to determine the programing language used. Your folder structure should look like this:

Now commit the source code with git add . to add all files followed by git commit -m "Initial commit" and finally git push origin master to push the files to GitHub.

Create Azure Static Web App

Open Azure portal and create a new static web app, log in to your GitHub account and choose the ToDoList app

Click on Next: Build to move to the next screen and configure it as below. The artifact location is dist/AzTodoList but it can be different in your case depending on your angular project name. You can get the exact path from your angular.json file or run ng build and check your folder structure.

When you create the app, it will automatically created the necessary CI/CD on GitHub using GitHub Actions and you can view that by clicking on the link “Thank you for using Azure Static Web App! We have not received any content for your site yet. Click here to check the status of your GitHub Action runs.” . You can view the build status by going to your GitHub repo and click Actions

As you can see above, it failed few times because I put the Angular app in a folder inside the repo. Once I moved all the files from within the inner folder to the root folder, it worked.

Test the app

Now go back to your Azure Portal and in the overview tab for the static web app, click Browse and this is what you should see

In the next post, we will add the APIs that will be used to retrieve, add and delete ToDos

Source code: https://github.com/haitham-shaddad/ng-todo-list-az-static-webapp