練習 - 使用 GitHub 事件觸發 Azure 函式

已完成

在此練習中,您將會更新您的函式,以剖析來自 GitHub Webhook 承載的資訊並顯示結果。

更新您的函式以剖析 Webhook 承載

  1. 在 Azure 入口網站中,移至您先前建立的函數應用程式。

  2. 在 [函數應用程式] 窗格中,左側功能表窗格的 [函式] 下,選取 [函式]。 [函數應用程式] 的 [函式] 窗格隨即出現。

  3. 選取您建立的 HttpTrigger1。 您函式的 [HtttpTrigger1] 窗格隨即顯示。

  4. 在左側功能表窗格中,於 [開發人員] 底下,選取 [程式碼 + 測試]。 您函式的 [程式碼 + 測試] 窗格隨即顯示。

  5. 在程式碼上方的路徑中,從下拉式清單選取 [index.js]。 觸發程序的 JavaScript 隨即顯示。

  6. 使用下列程式碼來取代函式主體中的最後三行程式碼,以更新程式碼。

    if (req.body.pages[0].title){
        context.res = {
            body: "Page is " + req.body.pages[0].title + ", Action is " + req.body.pages[0].action + ", Event Type is " + req.headers['x-github-event']
        };
    }
    else {
        context.res = {
            status: 400,
            body: ("Invalid payload for Wiki event")
        };
    }
    

    此程式碼會從要求標頭擷取事件類型,以及從訊息本文擷取 title 和 action 欄位。 此資訊指出頁面已變更,可能已編輯頁面或建立新頁面。 然後,該程式碼會建構一個總結該動作的回應。 JavaScript 看起來應該像下面這樣:

    module.exports = async function (context, req) {
        context.log('JavaScript HTTP trigger function processed a request.');
    
        const name = (req.query.name || (req.body && req.body.name));
        const responseMessage = name
            ? "Hello, " + name + ". This HTTP triggered function executed successfully."
            : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
    
        if (req.body.pages[0].title){
            context.res = {
                body: "Page is " + req.body.pages[0].title + ", Action is " + req.body.pages[0].action + ", Event Type is " + req.headers['x-github-event']
            };
         }
         else {
            context.res = {
                status: 400,
                body: ("Invalid payload for Wiki event")
            };
        }
    }
    
  7. 在頂端功能列上,選取 [儲存]

使用 Gollum 事件觸發您的 Azure 函式

  1. 返回您的 GitHub 帳戶。

  2. 選取您要在此課程模組中使用的存放庫。

  3. 在頂端功能列中,選取 [Settings] (設定)。 [設定] 窗格隨即出現。

  4. 在側邊欄中,選取 [Webhooks]。 [Webhooks] 窗格隨即出現。

  5. 針對您的 Webhook,選取 [Edit] (編輯)。 [Webhooks/Manage webhook] (Webhook/管理 Webhook) 窗格隨即出現。

  6. 選取 [Recent Deliveries] \(最近的傳遞項目\) 索引標籤。

  7. 選取省略符號按鈕 (...),以選取最新 (頂端) 的傳遞項目。

  8. 按一下 [Redeliver] \(重新傳遞\)。

  9. 在 [重新傳遞承載?] 對話方塊中,選取 [是,重新傳遞此承載]。 此動作模擬您再次變更您的 Wiki 頁面。

  10. 選取省略符號按鈕 (...),以選取最新 (頂端) 的傳遞項目 (重新傳遞)。

  11. 選取 [回應] 索引標籤。您將看到 Webhook 如何觸發您的函式,接著剖析資訊並傳送如下文字的回應:

    Page is Home, Action is edited, Event Type is gollum