클라이언트 만들기(v4beta1)

클라이언트를 만듭니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

Go

CTS용 클라이언트 라이브러리를 설치하고 사용하는 방법은 CTS 클라이언트 라이브러리를 참조하세요. 자세한 내용은 CTS Go API 참조 문서를 확인하세요.

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"time"

	talent "cloud.google.com/go/talent/apiv4beta1"
	"cloud.google.com/go/talent/apiv4beta1/talentpb"
	"github.com/golang/protobuf/ptypes"
)

// createClientEvent creates a client event.
func createClientEvent(w io.Writer, projectID string, requestID string, eventID string, relatedJobNames []string) (*talentpb.ClientEvent, error) {
	ctx := context.Background()

	// Create an eventService client.
	c, err := talent.NewEventClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("talent.NewEventClient: %w", err)
	}
	defer c.Close()

	createTime, _ := ptypes.TimestampProto(time.Now())
	clientEventToCreate := &talentpb.ClientEvent{
		RequestId:  requestID,
		EventId:    eventID,
		CreateTime: createTime,
		Event: &talentpb.ClientEvent_JobEvent{
			JobEvent: &talentpb.JobEvent{
				Type: talentpb.JobEvent_VIEW,
				Jobs: relatedJobNames,
			},
		},
	}

	// Construct a createJob request.
	req := &talentpb.CreateClientEventRequest{
		Parent:      fmt.Sprintf("projects/%s", projectID),
		ClientEvent: clientEventToCreate,
	}

	resp, err := c.CreateClientEvent(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("CreateClientEvent: %w", err)
	}

	fmt.Fprintf(w, "Client event created: %v\n", resp.GetEvent())

	return resp, nil
}

Java

CTS용 클라이언트 라이브러리를 설치하고 사용하는 방법은 CTS 클라이언트 라이브러리를 참조하세요. 자세한 내용은 CTS Java API 참조 문서를 확인하세요.

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.talent.v4beta1.ClientEvent;
import com.google.cloud.talent.v4beta1.CreateClientEventRequest;
import com.google.cloud.talent.v4beta1.EventServiceClient;
import com.google.cloud.talent.v4beta1.JobEvent;
import com.google.cloud.talent.v4beta1.TenantName;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class JobSearchCreateClientEvent {

  public static void createClientEvent() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String tenantId = "your-tenant-id";
    String requestId = "your-req-id-from-response-metadata";
    String eventId = "your-unique-identifier-id";
    createClientEvent(projectId, tenantId, requestId, eventId);
  }

  // Creates a client event.
  public static void createClientEvent(
      String projectId, String tenantId, String requestId, String eventId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (EventServiceClient eventServiceClient = EventServiceClient.create()) {
      TenantName parent = TenantName.of(projectId, tenantId);

      // The timestamp of the event as seconds of UTC time since Unix epoch
      // For more information on how to create google.protobuf.Timestamps
      // See:
      // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto
      long seconds = 3L;
      Timestamp createTime = Timestamp.newBuilder().setSeconds(seconds).build();

      // The type of event attributed to the behavior of the end user
      JobEvent.JobEventType type = JobEvent.JobEventType.VIEW;

      // List of job names associated with this event
      String jobsElement = "projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]";
      String jobsElement2 = "projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]";

      List<String> jobs = Arrays.asList(jobsElement, jobsElement2);
      JobEvent jobEvent = JobEvent.newBuilder().setType(type).addAllJobs(jobs).build();
      ClientEvent clientEvent =
          ClientEvent.newBuilder()
              .setRequestId(requestId)
              .setEventId(eventId)
              .setCreateTime(createTime)
              .setJobEvent(jobEvent)
              .build();
      CreateClientEventRequest request =
          CreateClientEventRequest.newBuilder()
              .setParent(parent.toString())
              .setClientEvent(clientEvent)
              .build();
      ClientEvent response = eventServiceClient.createClientEvent(request);
      System.out.println("Created client event. ");
      System.out.println(response.toString());
    }
  }
}

Node.js

CTS용 클라이언트 라이브러리를 설치하고 사용하는 방법은 CTS 클라이언트 라이브러리를 참조하세요. 자세한 내용은 CTS Node.js API 참조 문서를 확인하세요.

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


const talent = require('@google-cloud/talent').v4;

/**
 * Creates a client event
 *
 * @param projectId {string} Your Google Cloud Project ID
 * @param tenantId {string} Identifier of the Tenant
 * @param requestId {string} A unique ID generated in the API responses.
 * Value should be set to the request_id from an API response.
 * @param eventId {string} A unique identifier, generated by the client application
 */
function sampleCreateClientEvent(projectId, tenantId, requestId, eventId) {
  const client = new talent.EventServiceClient();
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  // const requestId = '[request_id from ResponseMetadata]';
  // const eventId = '[Set this to a unique identifier]';
  const formattedParent = client.tenantPath(projectId, tenantId);

  // The timestamp of the event as seconds of UTC time since Unix epoch
  // For more information on how to create google.protobuf.Timestamps
  // See: https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto
  const seconds = 0;
  const createTime = {
    seconds: seconds,
  };

  // The type of event attributed to the behavior of the end user
  const type = 'VIEW';

  // List of job names associated with this event
  const jobsElement = 'projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]';
  const jobsElement2 =
    'projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]';
  const jobs = [jobsElement, jobsElement2];
  const jobEvent = {
    type: type,
    jobs: jobs,
  };
  const clientEvent = {
    requestId: requestId,
    eventId: eventId,
    createTime: createTime,
    jobEvent: jobEvent,
  };
  const request = {
    parent: formattedParent,
    clientEvent: clientEvent,
  };
  client
    .createClientEvent(request)
    .then(responses => {
      const response = responses[0];
      console.log('Created client event');
      console.log(`Response: ${response}`);
    })
    .catch(err => {
      console.error(err);
    });
}

Python

CTS용 클라이언트 라이브러리를 설치하고 사용하는 방법은 CTS 클라이언트 라이브러리를 참조하세요. 자세한 내용은 CTS Python API 참조 문서를 확인하세요.

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


from google.cloud import talent
from google.cloud.talent import enums


def create_client_event(project_id, tenant_id, request_id, event_id):
    """
    Creates a client event

    Args:
      project_id Your Google Cloud Project ID
      tenant_id Identifier of the Tenant
      request_id A unique ID generated in the API responses.
      Value should be set to the request_id from an API response.
      event_id A unique identifier, generated by the client application
    """

    client = talent.EventServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # request_id = '[request_id from ResponseMetadata]'
    # event_id = '[Set this to a unique identifier]'

    if isinstance(project_id, bytes):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, bytes):
        tenant_id = tenant_id.decode("utf-8")
    if isinstance(request_id, bytes):
        request_id = request_id.decode("utf-8")
    if isinstance(event_id, bytes):
        event_id = event_id.decode("utf-8")
    parent = f"projects/{project_id}/tenants/{tenant_id}"

    # The timestamp of the event as seconds of UTC time since Unix epoch
    # For more information on how to create google.protobuf.Timestamps
    # See:
    # https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto
    seconds = 0
    create_time = {"seconds": seconds}

    # The type of event attributed to the behavior of the end user
    type_ = enums.JobEvent.JobEventType.VIEW

    # List of job names associated with this event
    jobs_element = "projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]"
    jobs_element_2 = "projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]"
    jobs = [jobs_element, jobs_element_2]
    job_event = {"type": type_, "jobs": jobs}
    client_event = {
        "request_id": request_id,
        "event_id": event_id,
        "create_time": create_time,
        "job_event": job_event,
    }

    response = client.create_client_event(parent=parent, client_event=client_event)
    print(response)

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.