演習 - ストレージ アカウントを使用して静的な Web サイトをホストする

完了

これで API がクラウドにデプロイされたので、Tailwind Traders のエンジニアとして、クライアント コードを更新し、それをデプロイして、Azure Functions 向けの SignalR メッセージをサポートする必要があります。

クライアント アプリケーションを更新する

  1. Visual Studio Code で、./start/client/src/index.js を開き、SignalR メッセージをリッスンするすべてのコードを置き換えます。 このコードは、HTTP 要求により初期株式リストを取得し、SignalR 接続からの更新をリッスンします。 株が更新されると、クライアントは UI で株価を更新します。

    import './style.css';
    import { BACKEND_URL } from './env';
    
    const app = new Vue({
        el: '#app',
        data() {
            return {
                stocks: []
            }
        },
        methods: {
            async getStocks() {
                try {
    
                    const url = `${BACKEND_URL}/api/getStocks`;
                    console.log('Fetching stocks from ', url);
    
                    const response = await fetch(url);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);
                    }
                    app.stocks = await response.json();
                } catch (ex) {
                    console.error(ex);
                }
            }
        },
        created() {
            this.getStocks();
        }
    });
    
    const connect = () => {
    
        const signalR_URL = `${BACKEND_URL}/api`;
        console.log(`Connecting to SignalR...${signalR_URL}`)
    
        const connection = new signalR.HubConnectionBuilder()
                                .withUrl(signalR_URL)
                                .configureLogging(signalR.LogLevel.Information)
                                .build();
    
        connection.onclose(()  => {
            console.log('SignalR connection disconnected');
            setTimeout(() => connect(), 2000);
        });
    
        connection.on('updated', updatedStock => {
            console.log('Stock updated message received', updatedStock);
            const index = app.stocks.findIndex(s => s.id === updatedStock.id);
            console.log(`${updatedStock.symbol} Old price: ${app.stocks[index].price}, New price: ${updatedStock.price}`);
            app.stocks.splice(index, 1, updatedStock);
        });
    
        connection.start().then(() => {
            console.log("SignalR connection established");
        });
    };
    
    connect();
    
  2. ./start/client/index.html を開き、アプリの ID がある現在の DIV の代わりに以下のコードを貼り付けます。

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css"
            integrity="sha256-8B1OaG0zT7uYA572S2xOxWACq9NXYPQ+U5kHPV1bJN4=" crossorigin="anonymous" />
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
            integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
        <title>Stock Notifications | Enable automatic updates in a web application using Azure Functions and SignalR</title>
    </head>
    
    <body>
        <div id="app" class="container">
            <h1 class="title">Stocks</h1>
            <div id="stocks">
                <div v-for="stock in stocks" class="stock">
                    <transition name="fade" mode="out-in">
                        <div class="list-item" :key="stock.price">
                            <div class="lead">{{ stock.symbol }}: ${{ stock.price }}</div>
                            <div class="change">Change:
                                <span
                                    :class="{ 'is-up': stock.changeDirection === '+', 'is-down': stock.changeDirection === '-' }">
                                    {{ stock.changeDirection }}{{ stock.change }}
                                </span>
                            </div>
                        </div>
                    </transition>
                </div>
            </div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"
            integrity="sha256-chlNFSVx3TdcQ2Xlw7SvnbLAavAQLO0Y/LBiWX04viY=" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.0/signalr.min.js"></script>
        <script src="bundle.js" type="text/javascript"></script>
    </body>
    </html>
    

    このマークアップには transition 要素が含まれています。これにより、Vue.js では、株式データが変更されたときに繊細なアニメーションを実行できるようになります。 株式が更新されたときに、タイルがフェードアウトし、すぐにまた表示されます。 このようにして、ページが株式データでいっぱいになった場合、ユーザーは変更された株式を簡単に確認することができます。

  3. bundle.js への参照のすぐ上に以下のスクリプト ブロックを追加して、SignalR SDK. を含めます。

    <script src="https://cdn.jsdelivr.net/npm/@aspnet/signalr@1.0.3/dist/browser/signalr.js"></script>
    

クライアント .env を更新する

  1. client/start フォルダーに .env という名前の環境変数ファイルを作成します。

  2. BACKEND_URL という名前の変数を追加し、ユニット 5 からコピーした値を追加します。

    BACKEND_URL=https://YOUR-FUNTIONS-APP-NAME.azurewebsites.net
    

Azure Static Web Apps リソースの作成とクライアントのデプロイ

  1. Azure portal を開き、新しい Azure Static Web Apps リソースを作成します。

  2. 次の情報を使用して、リソース作成の [基本] を完了します。

    名前
    サブスクリプション サブスクリプションを選択します。
    Resource group リソース グループ stock-prototype を使用します。
    静的 Web アプリ名 自分の名前を client の後ろに追加します。 たとえば、client-jamie のようにします。
    ホスティング プランの種類 [無料] を選択します。
    デプロイ ソース [GitHub] を選択します。
    組織 GitHub アカウントを選択する
    リポジトリ mslearn-advocates.azure-functions-and-signalr を検索して選びます。
    [Branch]\(ブランチ) main ブランチを選択します。
    Build Presets (ビルドのプリセット) [Vue.js] を選択します。
    アプリの場所 /start/client」と入力します。
    API の場所 空のままにします。
    出力場所 dist」と入力します。
  3. プレビュー ワークフロー ファイルを選択して、デプロイ設定を確認します。 ビルドとデプロイのステップは次のようになります。

    - name: Build And Deploy
      id: builddeploy
      uses: Azure/static-web-apps-deploy@v1
      with:
        azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_123 }}
        repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments)
        action: "upload"
        ###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
        # For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
        app_location: "/solution/client" # App source code path
        api_location: "" # Api source code path - optional
        output_location: "dist" # Built app content directory - optional
        ###### End of Repository/Build Configurations ######
    
  4. [閉じる] を選択して変更を保存します。

  5. [確認と作成] を選択し、次に [作成] を選択してリソースを作成します。 デプロイが完了するまで待ってから次に進みます。

  6. [リソースに移動] を選択して、新しい Azure Static Web Apps リソースを開きます。

  7. [概要] ページで、[URL] の値をコピーします。 これは、デプロイされた静的 Web アプリのベース URL です。

BACKEND_URL 変数をリポジトリに追加する

ワークフローでは、BACKEND_URL 環境変数をユニット 5 からデプロイされた Azure Functions アプリのベース URL に設定する必要があります。

  1. サンプル リポジトリの GitHub フォーク用のブラウザーで、[設定] -> [セキュリティ] -> [シークレットと変数] -> [アクション] の順に選択します。

  2. [変数] を選択し、[新しいリポジトリ変数] を選択します。

  3. 次の表を使用して変数を作成します。

    名前
    BACKEND_URL デプロイされた Azure Functions アプリのベース URL。 URL は、https://<FUNCTIONS-RESOURCE-NAME>.azurewebsites.net の形式にする必要があります
  4. [変数の追加] を選択して、変数をリポジトリに保存します。

GitHub デプロイ ワークフローの編集

  1. Visual Studio Code ターミナルで、フォーク (origin) から新しいワークフロー ファイルをプルダウンします。

    git pull origin main
    
  2. .github/workflows/azure-static-web-apps-*.yml ファイルを開きます。

  3. ファイルの上部にある name 値を Client に変更します。

  4. [ビルドとデプロイ] ステップを編集して、BACKEND_URL 環境変数の env プロパティを追加します。

    ```yaml
        name: Client - Azure Static Web Apps CI/CD
        
        on:
          push:
            branches:
              - main
          pull_request:
            types: [opened, synchronize, reopened, closed]
            branches:
              - main
        
        jobs:
          build_and_deploy_job:
            if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
            runs-on: ubuntu-latest
            name: Build and Deploy Job
            steps:
    
              - uses: actions/checkout@v3
                with:
                  submodules: true
                  lfs: false
    
              #Debug only - Did GitHub action variable get into workflow correctly?
              - name: Echo
                run: |
                  echo "BACKEND_URL: ${{ vars.BACKEND_URL }}"
    
              - name: Build And Deploy
                id: builddeploy
                uses: Azure/static-web-apps-deploy@v1
                with:
                  azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_123 }}
                  repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments)
                  action: "upload"
                  ###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
                  # For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
                  app_location: "/solution/client" # App source code path
                  api_location: "" # Api source code path - optional
                  output_location: "dist" # Built app content directory - optional
                  ###### End of Repository/Build Configurations ######
                env: 
                  BACKEND_URL: ${{ vars.BACKEND_URL }}
    
          close_pull_request_job:
            if: github.event_name == 'pull_request' && github.event.action == 'closed'
            runs-on: ubuntu-latest
            name: Close Pull Request Job
            steps:
              - name: Close Pull Request
                id: closepullrequest
                uses: Azure/static-web-apps-deploy@v1
                with:
                  azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_123 }}
                  action: "close"
        ```
    
  5. 変更を保存してリポジトリへプッシュします。

    git add .
    git commit -m "Add BACKEND_URL environment variable"
    git push
    
  6. GitHub フォーク リポジトリの [アクション] タブを開き、デプロイを監視します。

関数アプリで CORS を更新する

既定では、関数アプリでは CORS 要求は許可されません。 静的 Web アプリからの要求を許可するように関数アプリを更新する必要があります。

  1. Azure portal で、ユニット 5 で作成した Azure Functions アプリに移動します。

  2. 左側のメニューで [API] -> [CORS] を選択します

  3. [Enable Access-Control-Allow-Credentials] (Access-Control-Allow-Credentials を有効にする) を選びます。

  4. Static Web Apps リソース URL 用にコピーした値を追加します。

    プロパティ
    許可されたオリジン デプロイされた静的 Web アプリのベース URL。
  5. [保存] を選択して CORS 設定を保存します。

クライアントのデプロイをテストする

  1. ブラウザーで、デプロイされた静的 Web アプリの URL を使用してクライアントを開きます。
  2. 開発者ツールを開いてコンソールを監視し、更新された株式の SignalR データをいつ受信するかを確認します。 これらは HTTP 要求でないため、[ネットワーク] タブには表示されません。

お疲れさまでした。 SignalR を使用して改善した株式アプリをデプロイしました。