מחיקה של DataSource

קוד לדוגמה של Merchant API למחיקת מקור נתונים

// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package shopping.merchant.samples.datasources.v1beta;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1beta.DataSourceName;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.DeleteDataSourceRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to delete a datasource. */
public class DeleteDataSourceSample {

  public static void deleteDataSource(Config config, String dataSourceId) throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    DataSourcesServiceSettings dataSourcesServiceSettings =
        DataSourcesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String name =
        DataSourceName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .setDatasource(dataSourceId)
            .build()
            .toString();

    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {
      DeleteDataSourceRequest request = DeleteDataSourceRequest.newBuilder().setName(name).build();

      System.out.println("Sending deleteDataSource request");
      // Delete works for any datasource type.
      // If Type "Supplemental", delete will only work if it's not linked to any primary feed.
      // If a link exists and the Type is "Supplemental", you will need to remove the supplemental
      // feed from the default and/or custom rule(s) of any primary feed(s) that references it. Then
      // retry the delete.

      dataSourcesServiceClient.deleteDataSource(request); // No response returned on success.
      System.out.println(
          "Delete successful, note that it may take a few minutes for the delete to update in"
              + " the system.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // An ID automatically assigned to the datasource after creation by Google.
    String dataSourceId = "1111111111"; // Replace with your datasource ID.

    deleteDataSource(config, dataSourceId);
  }
}
<?php
/**
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../Authentication/Authentication.php';
require_once __DIR__ . '/../../Authentication/Config.php';
use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\DataSources\V1beta\Client\DataSourcesServiceClient;
use Google\Shopping\Merchant\DataSources\V1beta\DeleteDataSourceRequest;

/**
 * Class to demonstrate deleting a datasource.
 */
class DeleteDataSourceSample
{
    // ENSURE you fill in the datasource ID for the sample to work.
    private const DATASOURCE_ID = 'INSERT_DATASOURCE_ID';

    /**
     * Deletes a DataSource.
     *
     * @param int $merchantId The Merchant Center Account ID.
     * @param string $dataSourceId The data source ID.
     */
    public function deleteDataSource(int $merchantId, string $dataSourceId): void
    {
        // Gets the OAuth credentials to make the request.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates options config containing credentials for the client to use.
        $options = ['credentials' => $credentials];

        // Creates a client.
        $dataSourcesServiceClient = new DataSourcesServiceClient($options);

        // Creates the data source name.
        $name = sprintf('accounts/%s/dataSources/%s', $merchantId, $dataSourceId);

        // Creates the request.
        $request = (new DeleteDataSourceRequest())
            ->setName($name);

        print('Sending deleteDataSource request' . PHP_EOL);

        // Calls the API and catches and prints any network failures/errors.
        try {
            $dataSourcesServiceClient->deleteDataSource($request);
            print('Delete successful, note that it may take a few minutes for the delete to update in the system.' . PHP_EOL);
        } catch (ApiException $ex) {
            print('Call failed with message: ' . $ex->getMessage() . PHP_EOL);
        }
    }

    // Helper to execute the sample.
    public function callSample(): void
    {
        $config = Config::generateConfig();
        // The Merchant Center Account ID.
        $merchantId = $config['accountId'];

        self::deleteDataSource($merchantId, self::DATASOURCE_ID);
    }
}

$sample = new DeleteDataSourceSample();
$sample->callSample();
# -*- coding: utf-8 -*-
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A module to delete a DataSource."""

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_datasources_v1beta

# ENSURE you fill in the datasource ID for the sample to
# work.
_ACCOUNT = configuration.Configuration().read_merchant_info()
# An ID automatically assigned to the datasource after creation by Google.
_DATASOURCE = "[INSERT_DATASOURCE_HERE]"
_NAME = f"accounts/{_ACCOUNT}/dataSources/{_DATASOURCE}"


def delete_data_source():
  """Deletes the specified `DataSource` resource.

  Delete works for any datasource type.
  If Type "Supplemental", delete will only work if it's not linked to any
  primary feed. If a link exists and the Type is "Supplemental", you will need
  to remove the supplemental feed from the default and/or custom rule(s) of any
  primary feed(s) that references it. Then retry the delete.
  """

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = merchant_datasources_v1beta.DataSourcesServiceClient(
      credentials=credentials
  )

  # Creates the request.
  request = merchant_datasources_v1beta.DeleteDataSourceRequest(name=_NAME)

  # Makes the request and catches and prints any error messages.
  try:
    # No response is returned on request.
    client.delete_data_source(request=request)
    print("Deletion successful")
  except RuntimeError as e:
    print("Deletion failed")
    print(e)


if __name__ == "__main__":
  delete_data_source()