建置應用程式時,您通常會與後端 API 互動。 有時候,這些 API 尚無法使用,或其他小組正在更新它們以符合最新的需求。 為了避免等候,您通常會建立模擬 API 來傳回您需要的數據。 雖然此方法可以解除您的封鎖,但這需要您花時間建置一個最終會被實際 API 取代的暫時性 API。 若要避免浪費時間,您可以使用開發 Proxy 來模擬 CRUD API 並加速開發。
使用 CrudApiPlugin,您可以使用記憶體資料庫來模擬 CRUD(建立、讀取、更新、刪除)API。 使用簡單的組態檔,您可以定義模擬 API 支援的 URL 及其傳回的數據。 此插件也支援用戶端應用程式的跨域 CORS 使用。
在 MockResponsePlugin 定義靜態模擬回應時,CrudApiPlugin 允許您定義一個動態模擬 API,透過它您可以與數據互動,並查看您所做的更改如何反映在模擬數據集中。
情境
例如,您正在建置可讓使用者管理客戶的應用程式。 若要取得數據,您必須呼叫 /customers 後端 API 的端點。 為了避免等待後端小組完成其工作,您決定使用開發 Proxy 來模擬 API 並傳回您需要的數據。
您一開始會啟用 CrudApiPlugin ,並將其設定為使用 customers-api.json 檔案。
{
"name": "CrudApiPlugin",
"enabled": true,
"pluginPath": "~appFolder/plugins/DevProxy.Plugins.dll",
"configSection": "customersApi"
}
{
"customersApi": {
"apiFile": "customers-api.json"
}
}
在 檔案中 customers-api.json ,您會定義模擬客戶 API。
{
"$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v1.0.0/crudapiplugin.apifile.schema.json",
"baseUrl": "https://api.contoso.com/v1/customers",
"dataFile": "customers-data.json",
"actions": [
{
"action": "getAll"
},
{
"action": "getOne",
"url": "/{customer-id}",
"query": "$.[?(@.id == {customer-id})]"
},
{
"action": "create"
},
{
"action": "merge",
"url": "/{customer-id}",
"query": "$.[?(@.id == {customer-id})]"
},
{
"action": "delete",
"url": "/{customer-id}",
"query": "$.[?(@.id == {customer-id})]"
}
]
}
在 屬性中 baseUrl ,您會定義模擬 API 的基底 URL。 在屬性中 dataFile ,您會定義包含模擬客戶數據的檔案。 在屬性中 actions ,您可以定義支持的動作,以及它們對應至 HTTP 方法和 URL 的方式。 您想要使用你的 API 來:
- 透過呼叫來取得所有客戶
GET /v1/customers - 透過通話取得單一客戶
GET /v1/customers/{customer-id} - 藉由呼叫
POST /v1/customers來新增客戶。 - 藉由呼叫
PATCH /v1/customers/{customer-id}來更新客戶。 - 藉由呼叫該函數
DELETE /v1/customers/{customer-id}來刪除客戶
在您的 URL 中,您會使用 {customer-id} 參數,插件會將其替換為網址中的實際客戶 ID。 外掛程式也會使用 {customer-id} JSONPath 查詢中的 參數來查閱數據檔中的客戶。
在檔案中 customers-data.json ,您會定義模擬客戶數據。
[
{
"id": 1,
"name": "Contoso",
"address": "4567 Main St Buffalo, NY 98052"
},
{
"id": 2,
"name": "Fabrikam",
"address": "4567 Main St Buffalo, NY 98052"
}
]
您啟動開發代理伺服器並呼叫https://api.contoso.com/v1/customers 這個端點。 Dev Proxy 會攔截要求並傳回模擬客戶數據。
[
{
"id": 1,
"name": "Contoso",
"address": "4567 Main St Buffalo, NY 98052"
},
{
"id": 2,
"name": "Fabrikam",
"address": "4567 Main St Buffalo, NY 98052"
}
]
後續步驟
深入瞭解 CrudApiPlugin。
範例
另請參閱相關的開發 Proxy 範例: