練習 - 讓函式變成符合 REST 架構

已完成

Products Manager API 即將進行重大的樣式升級,這都要感謝你,Tailwind Traders 開發人員。 在此練習中,您將透過修改設定檔案,將您稍早建立的所有函式轉換成符合 REST 架構的函式。

讓 GetProducts 路由傳送 RESTful

  1. 在 Visual Studio Code 中,開啟 api/src/index.ts 檔案。

  2. GetProducts 的 路由定義中,限制 methods 屬性,使其只包含值 GET

    methods: ['GET']
    
  3. 針對 /api/products 的完整路由新增值為 productsroute 屬性。

    route: 'products',
    

    完整路由定義為:

    app.http('GetProducts', {
        methods: ['GET'],
        route: 'products',       // <- route: /api/products
        authLevel: 'anonymous',
        handler: GetProducts
    });
    
  4. 儲存檔案。

    注意

    儲存檔案將導致 Azure Functions 處理序終止偵錯工具,而其將中斷連線。 別擔心。 您沒有造成任何東西損壞。 這僅僅是您對函式的使用方式進行了基本的變更,因此當您完成所有的 REST 春季大掃除時,必須重新啟動專案。

讓 CreateProduct 函式變成符合 REST 架構

  1. api/src/index.ts 檔案中,將允許 methods 的屬性限制為 POST

    methods: ['POST']
    
  2. 針對 /api/products 的完整路由新增值為 productsroute 屬性。

    route: 'products',
    

    完整路由定義為:

    app.http('CreateProduct',{
        methods: ['POST'],
        route: 'products',
        authLevel: 'anonymous',
        handler: CreateProduct
    });
    
  3. 儲存檔案。

讓 UpdateProduct 函式變成符合 REST 架構

  1. api/src/index.ts 檔案中,將允許的 methods 屬性限制為 PUT

    methods: ['PUT'],
    
  2. 針對 /api/products 的完整路由新增值為 productsroute 屬性。

    route: 'products',
    

    完整路由定義為:

    app.http('UpdateProduct', {
        methods: ['PUT'],
        route: 'products',
        authLevel: 'anonymous',
        handler: UpdateProduct
    });
    
  3. 儲存檔案。

讓 DeleteProduct 函式變成符合 REST 架構

  1. api/src/index.ts 檔案中,將允許 methods 的屬性限制為 DELETE

     methods: ['DELETE']
    
  2. 更新路由,以使用產品識別碼作為路由參數。

    route: 'products/{id}',
    

    完整路由定義為:

    app.http('DeleteProduct', {
        methods: ['DELETE'],
        route: 'products/{id}',
        authLevel: 'anonymous',
        handler: DeleteProduct
    });
    
  3. 儲存檔案。

啟動專案

  1. 透過按下 F5 以啟動 Azure Functions 專案。

  2. 請注意,您函式端點的 URL 現在不同了。

    Visual Studio Code 終端的螢幕擷取畫面,其中顯示正在新路由上執行的端點。

查看那個令人驚豔的 API。 簡直太出色了。 請注意您如何為 CreateProduct、UpdateProduct 與 DeleteProduct 函式指定完全相同的路由。 只有 HTTP 要求方法不同。 您已經將三個 URL 轉換成一個,但仍有三個端點。 您是魔術師。