Use hooks to intercept queries, streams, mutations, and services
masterHooks allow you to execute logic before, after, or on error for various operations.
Pre-request hooks (executed before)
onQueryStart: Forqueryandreport.onStreamStart: ForreportStreamandreportStreamRaw.onMutationStart: For mutations.onServiceStart: For services.
Capabilities:
cancel(alternativeValue): Cancels the action. ThealternativeValuebecomes the return value of the operation.editOptions(options): Modifies request options (e.g., settingvalidate_only: true).
Error hooks (executed on error)
onQueryError: Forqueryandreport.onStreamError: ForreportStream(notreportStreamRaw).onMutationError: For mutations.onServiceError: For services.
Post-request hooks (executed after)
onQueryEnd: Forqueryandreport.onMutationEnd: For mutations.onServiceEnd: For services.
Note: There is no onStreamEnd hook to avoid blocking the thread or accumulating stream results.
import { OnQueryStart, OnQueryError, OnQueryEnd } from "google-ads-api";
// Example: Pre-request hook
const onQueryStart: OnQueryStart = async ({ cancel, editOptions }) => {
if (env.mode === "test") {
cancel([]); // Cancels and returns [] as the result
}
if (env.mode === "dev") {
editOptions({ validate_only: true });
}
};
// Example: Error hook
const onQueryError: OnQueryError = async ({ error }) => {
console.log(error.message);
};
// Example: Post-request hook
const onQueryEnd: OnQueryEnd = async ({ response, resolve }) => {
const [first] = response;
resolve([first]);
};
const customer = client.Customer(
{ clientOptions, customerOptions },
{ onQueryStart, onQueryError, onQueryEnd }
);