跳至主要內容

Workflow.map()

.map() 方法會將前一步驟的輸出資料對應至後續步驟的輸入,讓你能在步驟之間轉換資料。

使用範例
「使用範例」的直接連結

workflow.map(async ({ inputData }) => `${inputData.value} - map`)

參數
「參數」的直接連結

mappingFunction:

(params: { inputData: any }) => any
轉換輸入資料並回傳對應結果的函式

回傳值
「回傳值」的直接連結

workflow:

Workflow
可供方法連結使用的 Workflow 執行個體

使用 inputData
「using-inputdata」的直接連結

使用 inputData 存取前一步驟的完整輸出。

.then(step1)
.map(({ inputData }) => {
console.log(inputData);
})

使用 getStepResult()
「using-getstepresult」的直接連結

使用 getStepResult(),透過參照特定步驟的執行個體,存取該步驟的完整輸出。

.then(step1)
.map(async ({ getStepResult }) => {
console.log(getStepResult(step1));
})

使用 getInitData()
「using-getinitdata」的直接連結

使用 getInitData<typeof workflow>() 存取提供給 Workflow 的初始輸入資料。

.then(step1)
.map(async ({ getInitData }) => {
console.log(getInitData<any>());
})

使用 mapVariable()
「using-mapvariable」的直接連結

.map() 的物件形式提供另一種宣告式欄位對應語法。你不必撰寫函式,而是定義一個物件,其中每個 key 都是新的欄位名稱,每個 value 則使用 mapVariable() 從前一步驟或 Workflow 輸入擷取資料。 從 workflows 模組匯入 mapVariable()

import { mapVariable } from '@mastra/core/workflows'

從步驟輸出擷取欄位
「從步驟輸出擷取欄位」的直接連結

搭配 step 使用 mapVariable(),從步驟輸出擷取特定欄位並將其對應至新的欄位名稱。path 參數指定要擷取的欄位。 在此範例中,會從 step1 的輸出擷取 value 欄位,並對應至名為 details 的新欄位:

.then(step1)
.map({
details: mapVariable({
step: step1,
path: "value"
})
})

從 Workflow 輸入擷取欄位
「從 Workflow 輸入擷取欄位」的直接連結

搭配 initData 使用 mapVariable(),從 Workflow 的初始輸入資料擷取特定欄位。需要將原始 Workflow 輸入傳給後續步驟時,這項功能很實用。 在此範例中,會從 Workflow 輸入擷取 value 欄位,並對應至名為 details 的欄位:

export const testWorkflow = createWorkflow({...});

testWorkflow
.then(step1)
.map({
details: mapVariable({
initData: testWorkflow,
path: "value"
})
})