練習 - 讓函式變成符合 REST 架構
Products Manager API 即將進行重大的樣式升級,這都要感謝你,Tailwind Traders 開發人員。 在此練習中,您將透過修改設定檔案,將您稍早建立的所有函式轉換成符合 REST 架構的函式。
讓 GetProducts 路由傳送 RESTful
在 Visual Studio Code 中,開啟
api/src/index.ts
檔案。在 GetProducts 的 路由定義中,限制
methods
屬性,使其只包含值GET
。methods: ['GET']
針對
/api/products
的完整路由新增值為products
的route
屬性。route: 'products',
完整路由定義為:
app.http('GetProducts', { methods: ['GET'], route: 'products', // <- route: /api/products authLevel: 'anonymous', handler: GetProducts });
儲存檔案。
注意
儲存檔案將導致 Azure Functions 處理序終止偵錯工具,而其將中斷連線。 別擔心。 您沒有造成任何東西損壞。 這僅僅是您對函式的使用方式進行了基本的變更,因此當您完成所有的 REST 春季大掃除時,必須重新啟動專案。
讓 CreateProduct 函式變成符合 REST 架構
在
api/src/index.ts
檔案中,將允許methods
的屬性限制為POST
。methods: ['POST']
針對
/api/products
的完整路由新增值為products
的route
屬性。route: 'products',
完整路由定義為:
app.http('CreateProduct',{ methods: ['POST'], route: 'products', authLevel: 'anonymous', handler: CreateProduct });
儲存檔案。
讓 UpdateProduct 函式變成符合 REST 架構
在
api/src/index.ts
檔案中,將允許的methods
屬性限制為PUT
。methods: ['PUT'],
針對
/api/products
的完整路由新增值為products
的route
屬性。route: 'products',
完整路由定義為:
app.http('UpdateProduct', { methods: ['PUT'], route: 'products', authLevel: 'anonymous', handler: UpdateProduct });
儲存檔案。
讓 DeleteProduct 函式變成符合 REST 架構
在
api/src/index.ts
檔案中,將允許methods
的屬性限制為DELETE
。methods: ['DELETE']
更新路由,以使用產品識別碼作為路由參數。
route: 'products/{id}',
完整路由定義為:
app.http('DeleteProduct', { methods: ['DELETE'], route: 'products/{id}', authLevel: 'anonymous', handler: DeleteProduct });
儲存檔案。
啟動專案
透過按下 F5 以啟動 Azure Functions 專案。
請注意,您函式端點的 URL 現在不同了。
查看那個令人驚豔的 API。 簡直太出色了。 請注意您如何為 CreateProduct、UpdateProduct 與 DeleteProduct 函式指定完全相同的路由。 只有 HTTP 要求方法不同。 您已經將三個 URL 轉換成一個,但仍有三個端點。 您是魔術師。