ビルダー

Google 広告 スクリプトでエンティティを作成する場合は、通常ビルダーを使用します。ビルダーを使用すると、Google 広告エンティティを同期的または非同期的に構築できます。また、オペレーションが成功したかどうかを確認し、オペレーションの結果に応じて適切なアクションを取ることもできます。次のコード スニペットは、ビルダーを使用してキーワードを作成する方法を示しています。

// Retrieve your ad group.
let adGroup = AdsApp.adGroups().get().next();

// Create a keyword operation.
let keywordOperation = adGroup.newKeywordBuilder()
    .withCpc(1.2)
    .withText("shoes")
    .withFinalUrl("http://www.example.com/shoes")
    .build();

// Optional: examine the outcome. The call to isSuccessful()
// will block until the operation completes.
if (keywordOperation.isSuccessful()) {
  // Get the result.
  let keyword = keywordOperation.getResult();
} else {
  // Handle the errors.
  let errors = keywordOperation.getErrors();
}

Google 広告スクリプトを使って作成可能なエンティティは、このビルダー パターンを使って作成します。

パフォーマンスに関する注意事項

Google 広告 スクリプトの操作はデフォルトでは非同期で実行されます。これにより、スクリプトでオペレーションをバッチとしてグループ化し、高パフォーマンスを実現できます。ただし、isSuccessful()getResult() などの Operation メソッドを呼び出すと、Google 広告スクリプトで保留中のオペレーションのリストがフラッシュされるため、パフォーマンスが低下する可能性があります。代わりに、オペレーションを格納する配列を作成し、その配列を反復処理して結果を取得します。

低いパフォーマンス パフォーマンス高
for (let i = 0; i < keywords.length; i++)
  let keywordOperation = adGroup
    .newKeywordBuilder()
    .withText(keywords[i])
    .build();

  // Bad: retrieving the result in the same
  // loop that creates the operation
  // leads to poor performance.
  let newKeyword =
      keywordOperation.getResult();
  newKeyword.applyLabel("New keywords”);
}
// Create an array to hold the operations
let operations = [];

for (let i = 0; i < keywords.length; i++) {
  let keywordOperation = adGroup
    .newKeywordBuilder()
    .withText(keywords[i])
    .build();
  operations.push(keywordOperation);
}

// Process the operations separately. Allows
// Google Ads scripts to group operations into
// batches.
for (let i = 0; i < operations.length; i++) {
  let newKeyword = operations[i].getResult();
  newKeyword.applyLabel("New keywords”);
}