Costruttori

I builder sono il modo standard per creare entità negli script Google Ads. I builder consentono di creare un'entità Google Ads in modo sincrono o asincrono. Puoi anche verificare se l'operazione è andata a buon fine o meno e intraprendere le azioni appropriate a seconda dell'esito dell'operazione. Il seguente snippet di codice mostra come creare una parola chiave utilizzando un builder.

// 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();
}

Qualsiasi entità che può essere creata utilizzando gli script Google Ads lo fa utilizzando questo pattern di builder.

Considerazioni sulle prestazioni

Per impostazione predefinita, gli script Google Ads eseguono le operazioni in modo asincrono. In questo modo, gli script possono raggruppare le operazioni in batch e ottenere prestazioni elevate. Tuttavia, chiamare i metodi Operation come isSuccessful() e getResult() impone agli script Google Ads di svuotare l'elenco delle operazioni in attesa e pertanto potrebbe comportare scarse prestazioni. Crea invece un array per contenere le operazioni, quindi scorri l'array per recuperare i risultati.

Prestazioni scarse Prestazioni buone
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");
}