Membuat dan mengelola pesan HL7v2

Halaman ini menjelaskan cara menyerap, membuat, memberi label, mencantumkan, melihat, dan menghapus pesan HL7v2. Pesan HL7v2 digunakan untuk mengirimkan data klinis antarsistem. Pesan HL7v2 mungkin berisi informasi tentang hasil pengamatan, resep yang akan dikirim ke apotek, transaksi keuangan, atau peristiwa klinis lainnya.

Ringkasan pembuatan dan penyerapan pesan HL7v2

Gunakan salah satu metode berikut untuk menyimpan pesan HL7v2 di Cloud Healthcare API:

Saat Anda menggunakan messages.ingest, metode ini akan menghasilkan respons yang berisi salah satu dari hal berikut:

  • Pesan konfirmasi (ACK) HL7v2 jika berhasil
  • Pesan konfirmasi negatif (NACK) saat terjadi error

Pesan ACK dan NACK digunakan untuk membalas sistem antarmuka HL7v2 yang mengharapkan konfirmasi ini.

Proses transfer dan pembuatan pesan dengan adaptor MLLP

Pesan HL7v2 dikirim antara sistem perawatan dan Cloud Healthcare API menggunakan minimal lower layer protocol (MLLP). Untuk informasi selengkapnya, lihat MLLP dan adaptor MLLP Google Cloud Platform. Untuk mengetahui petunjuk cara mengonfigurasi adaptor MLLP agar berkomunikasi dengan aman dengan Cloud Healthcare API, lihat Mengirim pesan HL7v2 melalui koneksi TCP/IP.

Menyerap pesan HL7v2

Setelah Cloud Healthcare API menyerap pesan dari sistem perawatan, Cloud Healthcare API akan menghasilkan respons yang berisi kolom hl7ack yang berisi pesan HL7v2 yang dienkode dengan base64 dengan karakteristik berikut:

  • Jenis pesannya adalah ACK.
  • Fasilitas pengiriman dan fasilitas penerimaan dibalik, dan aplikasi pengiriman dan aplikasi penerimaan dibalik.
  • Waktu pengiriman pesan adalah waktu saat ini dan ID kontrol baru dibuat.
  • Nilai kolom MSH-9.1 menentukan jenis pesan.
  • Nilai kolom MSA.1 menentukan jenis respons. Jenis respons AA menunjukkan Application Accept, yang berarti pesan telah divalidasi dan berhasil ditransfer.
  • Nilai MSA.2 berisi ID kontrol pesan asli.

Contoh berikut menunjukkan cara menyerap pesan HL7v2 menggunakan metode projects.locations.datasets.hl7V2Stores.messages.ingest.

curl

Untuk menyerap pesan HL7v2, buat permintaan POST dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • Message

Contoh berikut menunjukkan permintaan POST yang menggunakan curl dan contoh file JSON yang disebut hl7v2-sample.json.

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data-binary @hl7v2-sample.json \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages:ingest"

Contoh respons berikut menunjukkan hl7Ack dan detail pesan.

{
  "hl7Ack": "TVNIfF5+XCZ8QXxBfEF8U0VORF9GQUNJTElUWXwyMDIwMDIxNDIxMjAwNXx8QUNLfDFmMmQ1MjQzLTFhOWEtNGE4My05ZmI5LWNlNTIzMTVmZjk2M3xUfDAuMA1NU0F8QUF8MjAxODAxMDEwMDAwMDA=",
  "message": {
    "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
    "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwNDAwMDANUElEfHwxNAExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk9SR05NQlI=",
    "sendFacility": "SEND_FACILITY",
    "sendTime": "2018-01-01T00:00:00Z",
    "messageType": "TYPE",
    "createTime": "CREATE_TIME",
    "patientIds": [
      {
        "value": "14\u0001111",
        "type": "MRN"
      },
      {
        "value": "11111111",
        "type": "MRN"
      },
      {
        "value": "1111111111",
        "type": "ORGNMBR"
      }
    ]
  }
}

PowerShell

Untuk menyerap pesan HL7v2, buat permintaan POST dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • Message

Contoh berikut menunjukkan permintaan POST menggunakan PowerShell dan contoh file JSON yang disebut hl7v2-sample.json.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -InFile hl7v2-sample.json `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages:ingest" | Select-Object -Expand Content

Contoh respons berikut menunjukkan hl7Ack dan detail pesan.

{
  "hl7Ack": "TVNIfF5+XCZ8QXxBfEF8U0VORF9GQUNJTElUWXwyMDIwMDIxNDIxMjAwNXx8QUNLfDFmMmQ1MjQzLTFhOWEtNGE4My05ZmI5LWNlNTIzMTVmZjk2M3xUfDAuMA1NU0F8QUF8MjAxODAxMDEwMDAwMDA=",
  "message": {
    "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
    "data": "TVNIfF5+XCZ8QXxTRU5EX0ZBQ0lMSVRZfEF8QXwyMDE4MDEwMTAwMDAwMHx8VFlQRV5BfDIwMTgwMTAxMDAwMDAwfFR8MC4wfHx8QUF8fDAwfEFTQ0lJDUVWTnxBMDB8MjAxODAxMDEwNDAwMDANUElEfHwxNAExMTFeXl5eTVJOfDExMTExMTExXl5eXk1STn4xMTExMTExMTExXl5eXk9SR05NQlI=",
    "sendFacility": "SEND_FACILITY",
    "sendTime": "2018-01-01T00:00:00Z",
    "messageType": "TYPE",
    "createTime": "CREATE_TIME",
    "patientIds": [
      {
        "value": "14\u0001111",
        "type": "MRN"
      },
      {
        "value": "11111111",
        "type": "MRN"
      },
      {
        "value": "1111111111",
        "type": "ORGNMBR"
      }
    ]
  }
}

Go

import (
	"context"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1"
)

// ingestHL7V2Message ingests an HL7V2 message.
func ingestHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, messageFile string) error {
	ctx := context.Background()

	hl7v2message, err := ioutil.ReadFile(messageFile)
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	req := &healthcare.IngestMessageRequest{
		Message: &healthcare.Message{
			Data: base64.StdEncoding.EncodeToString(hl7v2message),
		},
	}
	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s", projectID, location, datasetID, hl7V2StoreID)

	resp, err := messagesService.Ingest(parent, req).Do()
	if err != nil {
		return fmt.Errorf("Create: %w", err)
	}

	fmt.Fprintf(w, "Ingested HL7V2 message: %q\n", resp.Message.Name)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.IngestMessageRequest;
import com.google.api.services.healthcare.v1.model.IngestMessageResponse;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageIngest {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessageIngest(String hl7v2StoreName, String filePath) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Load the data from file and format it into an ingest request.
    List<String> lines = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset());
    String data = String.join("\n", lines);
    Message message = new Message().setData(data);
    IngestMessageRequest ingestRequest = new IngestMessageRequest().setMessage(message);

    // Create request and configure any parameters.
    Messages.Ingest request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .ingest(hl7v2StoreName, ingestRequest);

    // Execute the request and process the results.
    IngestMessageResponse response = request.execute();
    System.out.println("HL7v2 message ingested: " + response.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

const ingestHl7v2Message = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const hl7v2MessageFile = 'hl7v2-message.json';
  const hl7v2Message = JSON.parse(await readFile(hl7v2MessageFile));

  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent, resource: hl7v2Message};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.ingest(
      request
    );
  const data = response.data.hl7Ack;
  const buff = new Buffer.from(data, 'base64');
  const hl7Ack = buff.toString('ascii');
  console.log('Ingested HL7v2 message with ACK:\n', hl7Ack);
};

ingestHl7v2Message();

Python

def ingest_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_file
):
    """Ingests a new HL7v2 message from the hospital and sends a notification
    to the Cloud Pub/Sub topic. Return is an HL7v2 ACK message if the message
    was successfully stored.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    # Imports Python's built-in "json" module
    import json

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset ID
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    # hl7v2_message_file = 'hl7v2-message.json'  # replace with the path to the HL7v2 file
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_store_name = "{}/datasets/{}/hl7V2Stores/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id
    )

    with open(hl7v2_message_file) as hl7v2_message:
        hl7v2_message_content = json.load(hl7v2_message)

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .ingest(parent=hl7v2_store_name, body=hl7v2_message_content)
    )

    response = request.execute()
    print(f"Ingested HL7v2 message from file: {hl7v2_message_file}")
    return response

Membuat pesan HL7v2

Contoh berikut menunjukkan cara membuat pesan HL7v2 menggunakan metode projects.locations.datasets.hl7V2Stores.messages.create.

REST

Untuk membuat pesan HL7v2, gunakan metode projects.locations.datasets.hl7V2Stores.messages.create.

Jika memerlukan file pesan HL7v2 untuk digunakan dengan contoh perintah, Anda dapat mendownload file JSON hl7v2-sample.json.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: ID project Google Cloud Anda
  • LOCATION: lokasi set data
  • DATASET_ID: set data induk penyimpanan HL7v2
  • HL7V2_STORE_ID: ID penyimpanan HL7v2
  • HL7V2_MESSAGE_FILE: jalur ke file berformat JSON yang berisi pesan HL7v2 di komputer lokal Anda

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Jalankan perintah berikut:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
--data-binary @HL7V2_MESSAGE_FILE \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages"

PowerShell

Jalankan perintah berikut:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-InFile HL7V2_MESSAGE_FILE `
-Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages" | Select-Object -Expand Content

APIs Explorer

Buka halaman referensi metode. Panel API Explorer terbuka di sisi kanan halaman. Anda bisa berinteraksi dengan alat ini untuk mengirim permintaan. Lengkapi kolom yang wajib diisi, lalu klik Jalankan.

Output berikut ditampilkan saat membuat pesan menggunakan file JSON hl7v2-sample.json:

Go

import (
	"context"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1"
)

// createHL7V2Message creates an HL7V2 message.
func createHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, messageFile string) error {
	ctx := context.Background()

	hl7v2message, err := ioutil.ReadFile(messageFile)
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	req := &healthcare.CreateMessageRequest{
		Message: &healthcare.Message{
			Data: base64.StdEncoding.EncodeToString(hl7v2message),
		},
	}
	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s", projectID, location, datasetID, hl7V2StoreID)
	resp, err := messagesService.Create(parent, req).Do()
	if err != nil {
		return fmt.Errorf("Create: %w", err)
	}

	fmt.Fprintf(w, "Created HL7V2 message: %q\n", resp.Name)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.CreateMessageRequest;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageCreate {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessageCreate(String hl7v2StoreName, String messageId, String filePath)
      throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");
    // String messageId = "your-message-id";
    // String filePath = "path/to/file.txt";

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Load the data from file representing the message.
    List<String> lines = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset());
    String data = String.join("\n", lines);
    Message message = new Message().setData(data).setName(messageId);
    CreateMessageRequest createRequest = new CreateMessageRequest().setMessage(message);

    // Create request and configure any parameters.
    Messages.Create request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .create(hl7v2StoreName, createRequest);

    // Execute the request and process the results.
    Message response = request.execute();
    System.out.println("HL7v2 message created: " + response.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);

const createHl7v2Message = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // const hl7v2MessageFile = 'hl7v2-message.json';
  const hl7v2Message = JSON.parse(await readFile(hl7v2MessageFile));

  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent, resource: hl7v2Message};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.create(
      request
    );
  const {data} = response;
  console.log('Created HL7v2 message with data:\n', data);
};

createHl7v2Message();

Python

def create_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_file
):
    """Creates an HL7v2 message and sends a notification to the
    Cloud Pub/Sub topic.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    # Imports Python's built-in "json" module
    import json

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset ID
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    # hl7v2_message_file = 'hl7v2-message.json'  # replace with the path to the HL7v2 file
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_store_name = "{}/datasets/{}/hl7V2Stores/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id
    )

    with open(hl7v2_message_file) as hl7v2_message:
        hl7v2_message_content = json.load(hl7v2_message)

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .create(parent=hl7v2_store_name, body=hl7v2_message_content)
    )

    response = request.execute()
    print(f"Created HL7v2 message from file: {hl7v2_message_file}")
    return response

Pemisah dan encoding segmen pesan HL7v2

Pemisah segmen default di HL7v2 adalah carriage return (\r). Sebagian besar editor teks menggunakan karakter baris baru (\n) sebagai pemisah segmen. Hal ini menghasilkan pesan HL7v2 yang tidak dapat diserap ke dalam Cloud Healthcare API menggunakan konfigurasi default. Untuk mengizinkan penyimpanan HL7v2 menyerap pesan yang menggunakan karakter baris baru sebagai pemisah segmen, lihat Menetapkan terminator segmen.

Untuk mengonversi karakter baris baru dalam file menjadi carriage return, jalankan perintah berikut di shell Linux:

sed -z 's/\n/\r/g' INPUT_FILENAME > OUTPUT_FILENAME

Metode transfer dan pembuatan mengharapkan pesan HL7v2 berupa string berenkode base64. Untuk mengonversi string ke encoding base64, jalankan perintah berikut di shell Linux:

openssl base64 -A -in ./INPUT_FILENAME -out ./OUTPUT_FILENAME

Menetapkan terminator segmen

Saat membuat atau menyerap data, format pesan HL7v2 mengharuskan segmen dihentikan menggunakan karakter enter, \r. Anda dapat mengonfigurasi penyimpanan HL7v2 untuk menerima pesan HL7v2 dengan terminator non-standar, seperti \n.

Pertimbangkan pesan HL7v2 berikut yang menggunakan \r default sebagai terminator segmen. Pesan ini diterima secara default saat Anda membuat penyimpanan HL7v2.

MSH|^~\\&|FROM_APP|FROM_FACILITY|TO_APP|TO_FACILITY|20150503223000||ADT^A01|20150503223000|P|2.5|\r
EVN|A01|20110613083617|\r
PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439|\r
PV1||I|H73 RM1^1^^HIGHWAY 73 CLINIC||||5148^MARY QUINN|||||||||Y||||||||||||||||||||||||||||20150503223000|\r

Pesan berikut identik dengan pesan sebelumnya, kecuali bahwa pesan ini menggunakan \n sebagai terminator segmen:

MSH|^~\\&|FROM_APP|FROM_FACILITY|TO_APP|TO_FACILITY|20150503223000||ADT^A01|20150503223000|P|2.5|\n
EVN|A01|20110613083617|\n
PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439|\n
PV1||I|H73 RM1^1^^HIGHWAY 73 CLINIC||||5148^MARY QUINN|||||||||Y||||||||||||||||||||||||||||20150503223000|\n

Untuk menyimpan pesan dengan terminator non-standar, konfigurasikan objek ParserConfig di penyimpanan HL7v2 dan tetapkan kolom segmentTerminator ke encoding base64 \n.

Contoh berikut menunjukkan cara mengonfigurasi segmentTerminator di ParserConfig saat Anda membuat penyimpanan HL7v2. Jika sudah memiliki penyimpanan HL7v2, Anda dapat mengeditnya untuk memberikan isi ParserConfig. Setelah menetapkan terminator segmen, Anda dapat membuat atau menyerap pesan.

curl

Untuk membuat penyimpanan HL7v2 dengan terminator segmen yang disetel ke \n, buat permintaan POST dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • Objek parserConfig dengan segmentTerminator yang disetel ke Cg== (encoding base64 \n)

Contoh berikut menunjukkan permintaan POST yang menggunakan curl.

curl -X POST \
    --data "{
      'parserConfig': {
        'segmentTerminator': 'Cg=='
      }
    }" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID"

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "segmentTerminator": "Cg=="
  }
}

PowerShell

Untuk membuat penyimpanan HL7v2 dengan terminator segmen yang disetel ke \n, buat permintaan POST dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • Objek parserConfig dengan segmentTerminator yang disetel ke Cg== (encoding base64 \n)

Contoh berikut menunjukkan permintaan POST menggunakan PowerShell.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'parserConfig': {
        'segmentTerminator': 'Cg=='
      }
  } `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "segmentTerminator": "Cg=="
  }
}

Menggunakan header segmen null

Pesan HL7v2 tanpa segmen header pesan (MSH) memiliki header segmen null. Biasanya, pesan HL7v2 berisi MSH yang menentukan metadata seperti sumber, intent, tujuan, dan tujuan pesan. MSH memungkinkan Anda menelusuri dan memfilter pesan. Namun, Anda dapat menyimpan pesan yang tidak berisi MSH dengan mengonfigurasi objek ParserConfig di penyimpanan HL7v2 dan menetapkan kolom allowNullHeader ke true.

Contoh pesan berikut berisi segmen Identifikasi Pasien (PID), tetapi tidak ada MSH:

PID|1||21004053^^^^MRN||SULLY^BRIAN||19611209|M|||123 MAIN ST^^MOUNTAIN SPRINGS^CO^80439

Contoh berikut menunjukkan cara mengonfigurasi allowNullHeader di ParserConfig saat Anda membuat penyimpanan HL7v2. Jika sudah memiliki penyimpanan HL7v2, Anda dapat mengeditnya dan memberikan isi ParserConfig. Setelah menetapkan allowNullHeader ke true, Anda dapat membuat atau menyerap pesan dengan header segmen null.

curl

Untuk membuat penyimpanan HL7v2 dan menyimpan pesan yang tidak berisi MSH, buat permintaan POST dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • Objek parserConfig dengan allowNullHeader disetel ke true

Contoh berikut menunjukkan permintaan POST yang menggunakan curl.

curl -X POST \
    --data "{
      'parserConfig': {
        'allowNullHeader': true
      }
    }" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID"

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "allowNullHeader": true
  }
}

PowerShell

Untuk membuat penyimpanan HL7v2 dan menyimpan pesan yang tidak berisi MSH, buat permintaan POST dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • Objek parserConfig dengan allowNullHeader disetel ke true

Contoh berikut menunjukkan permintaan POST menggunakan PowerShell.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'parserConfig': {
        'nullTerminator': true
      }
  } `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores?hl7V2StoreId=HL7V2_STORE_ID" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID",
  "parserConfig": {
    "allowNullHeader": true
  }
}

Memberi label pada pesan HL7v2

Anda dapat menambahkan satu atau beberapa label nilai kunci ke pesan. Kasus penggunaan untuk label adalah menambahkan label status ke pesan sehingga aplikasi dapat mengkueri pesan berdasarkan status.

Contoh berikut menunjukkan cara menambahkan label ke pesan HL7v2 menggunakan metode projects.locations.datasets.hl7V2Stores.messages.patch.

curl

Untuk menambahkan label ke pesan HL7v2, buat permintaan PATCH dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • Data label yang akan diperbarui
  • Mask update

Contoh berikut menunjukkan permintaan PATCH yang menggunakan curl.

curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'labels': {
        'KEY' : 'VALUE'
      }
    }" "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?updateMask=labels"

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    }
  ],
  "labels": {
    "KEY": "VALUE"
  }
}

PowerShell

Untuk menambahkan label ke pesan HL7v2, buat permintaan PATCH dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • Data label yang akan diperbarui
  • Mask update

Contoh berikut menunjukkan permintaan PATCH menggunakan PowerShell.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Patch `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
      'labels': {
        'KEY': 'VALUE'
      }
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?updateMask=labels" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    }
  ],
  "labels": {
    "KEY": "VALUE"
  }
}

Go

import (
	"context"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"

	healthcare "google.golang.org/api/healthcare/v1"
)

// patchHL7V2Message patches an HL7V2 message.
func patchHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID, messageFile string) error {
	ctx := context.Background()

	hl7v2message, err := ioutil.ReadFile(messageFile)
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s", projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID)
	message := &healthcare.Message{
		Data:   base64.StdEncoding.EncodeToString(hl7v2message),
		Labels: map[string]string{"my-label": "true"},
	}

	call := messagesService.Patch(name, message)
	call.UpdateMask("labels")
	resp, err := call.Do()
	if err != nil {
		return fmt.Errorf("Patch: %w", err)
	}

	fmt.Fprintf(w, "Patched HL7V2 message: %q\n", resp.Name)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessagePatch {
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessagePatch(String hl7v2MessageName) throws IOException {
    // String hl7v2MessageName =
    //    String.format(
    //        MESSAGE_NAME, "project-id", "region-id", "dataset-id", "hl7v2-id", "message-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Fetch the initial state of the message.
    Messages.Get getRequest =
        client.projects().locations().datasets().hl7V2Stores().messages().get(hl7v2MessageName);
    Message message = getRequest.execute();

    // Update the Message fields as needed as needed. For a full list of Message fields, see:
    // https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.hl7V2Stores.messages
    Map<String, String> labels = new HashMap<>();
    labels.put("key1", "value1");
    labels.put("key2", "value2");
    message.setLabels(labels);

    // Create request and configure any parameters.
    Messages.Patch request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .messages()
            .patch(hl7v2MessageName, message)
            .setUpdateMask("labels");

    // Execute the request and process the results.
    message = request.execute();
    System.out.println("HL7v2 message patched: \n" + message.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const patchHl7v2Message = async () => {
  // TODO(developer): uncomment the lines beginning with 'const' before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // The value for hl7v2MessageId is the server-generated ID returned when you
  // created or ingested the HL7v2 message in an HL7v2 store.
  // const hl7v2MessageId = 'qCnewKno44gTt3oBn4dQ0u8ZA23ibDdV9GpifD2E=';
  // const labelKey = 'status';
  // const labelValue = 'processed';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  const request = {
    name,
    updateMask: 'labels',
    resource: {
      labels: {
        labelKey: labelValue,
      },
    },
  };

  await healthcare.projects.locations.datasets.hl7V2Stores.messages.patch(
    request
  );
  console.log('Patched HL7v2 message');
};

patchHl7v2Message();

Python

def patch_hl7v2_message(
    project_id,
    location,
    dataset_id,
    hl7v2_store_id,
    hl7v2_message_id,
    label_key,
    label_value,
):
    """Updates the message.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset ID
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    # hl7v2_message_id = '2yqbdhYHlk_ucSmWkcKOVm_N0p0OpBXgIlVG18rB-cw='  # replace with the HL7v2 message ID that was returned by the server
    # label_key = 'key1'  # replace with a key
    # label_value = 'label2'  # replace with a key value
    hl7v2_message_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message_name = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_message_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

    patch = {"labels": {label_key: label_value}}

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .patch(name=hl7v2_message_name, updateMask="labels", body=patch)
    )

    response = request.execute()
    print(
        "Patched HL7v2 message {} with labels:\n\t{}: {}".format(
            hl7v2_message_id, label_key, label_value
        )
    )
    return response

Mendapatkan konten pesan HL7v2

Contoh berikut menunjukkan cara mendapatkan konten pesan HL7v2 menggunakan metode projects.locations.datasets.hl7V2Stores.messages.get. Untuk menentukan bagian pesan yang akan diperoleh, berikan parameter kueri view dengan salah satu opsi berikut:

  • BASIC: Hanya sertakan kolom name.
  • RAW_ONLY: Menyertakan semua kolom pesan kecuali kolom parsedData.
  • PARSED_ONLY: Menyertakan semua kolom pesan kecuali kolom data.
  • FULL: Menyertakan semua kolom pesan. Ini adalah setelan defaultnya.

Contoh berikut menunjukkan cara mendapatkan konten pesan HL7v2 menggunakan tampilan FULL, RAW_ONLY, dan PARSED_ONLY.

Menggunakan tampilan FULL

Anda tidak perlu menetapkan tampilan FULL secara eksplisit, karena FULL adalah nilai default. Namun, dalam contoh curl dan PowerShell berikut, tampilan FULL ditambahkan sebagai parameter kueri untuk kelengkapan.

curl

Untuk mendapatkan konten pesan HL7v2 menggunakan tampilan FULL, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • FULL sebagai view

Contoh berikut menunjukkan permintaan GET yang menggunakan curl.

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=FULL"

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        ""segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

PowerShell

Untuk mendapatkan konten pesan HL7v2 menggunakan tampilan FULL, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • FULL sebagai view

Contoh berikut menunjukkan permintaan GET menggunakan PowerShell.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=FULL" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        ""segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

Go

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1"
)

// getHL7V2Message gets an HL7V2 message.
func getHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s", projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID)
	message, err := messagesService.Get(name).Do()
	if err != nil {
		return fmt.Errorf("Get: %w", err)
	}

	rawData, err := base64.StdEncoding.DecodeString(message.Data)
	if err != nil {
		return fmt.Errorf("base64.DecodeString: %w", err)
	}

	fmt.Fprintf(w, "Got HL7V2 message.\n")
	fmt.Fprintf(w, "Raw length: %d.\n", len(rawData))
	fmt.Fprintf(w, "Parsed data:\n")
	parsedJSON, _ := json.MarshalIndent(message.ParsedData, "", "  ")
	fmt.Fprintf(w, "%s", parsedJSON)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageGet {
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessageGet(String hl7v2MessageName) throws IOException {
    // String hl7v2MessageName =
    //    String.format(
    //        MESSAGE_NAME, "project-id", "region-id", "dataset-id", "hl7v2-id", "message-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Create request and configure any parameters.
    Messages.Get request =
        client.projects().locations().datasets().hl7V2Stores().messages().get(hl7v2MessageName);

    // Execute the request and process the results.
    Message store = request.execute();
    System.out.println("HL7v2 message retrieved: \n" + store.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getHl7v2Message = async () => {
  // TODO(developer): uncomment the lines beginning with 'const' before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // The value for hl7v2MessageId is the server-generated ID returned when you
  // created or ingested the HL7v2 message in an HL7v2 store.
  // const hl7v2MessageId = 'qCnewKno44gTt3oBn4dQ0u8ZA23ibDdV9GpifD2E=';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  // Use the 'FULL' enum to include all of the message fields in the response.
  const view = 'FULL';
  const request = {name, view};

  const hl7v2Message =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.get(
      request
    );
  console.log('Got HL7v2 message:\n', hl7v2Message.data);
};

getHl7v2Message();

Python

def get_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_id
):
    """Gets an HL7v2 message.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset ID
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    # hl7v2_message_id = '2yqbdhYHlk_ucSmWkcKOVm_N0p0OpBXgIlVG18rB-cw='  # replace with the HL7v2 message ID that was returned by the server
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message_name = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

    msgs = client.projects().locations().datasets().hl7V2Stores().messages()
    message = msgs.get(name=hl7v2_message_name).execute()

    print("Name: {}".format(message.get("name")))
    print("Data: {}".format(message.get("data")))
    print("Creation time: {}".format(message.get("createTime")))
    print("Sending facility: {}".format(message.get("sendFacility")))
    print("Time sent: {}".format(message.get("sendTime")))
    print("Message type: {}".format(message.get("messageType")))
    print("Patient IDs:")
    patient_ids = message.get("patientIds")
    for patient_id in patient_ids:
        print("\tPatient value: {}".format(patient_id.get("value")))
        print("\tPatient type: {}".format(patient_id.get("type")))
    print("Labels: {}".format(message.get("labels")))

    print(message)
    return message

Menggunakan tampilan RAW_ONLY

Contoh berikut menunjukkan cara mendapatkan konten pesan HL7v2 menggunakan tampilan RAW_ONLY, yang mencakup semua kolom pesan kecuali parsedData.

curl

Untuk mendapatkan konten pesan HL7v2 menggunakan tampilan RAW_ONLY, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • RAW_ONLY sebagai tampilan

Contoh berikut menunjukkan permintaan GET yang menggunakan curl.

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=RAW_ONLY"

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ]
}

PowerShell

Untuk mendapatkan konten pesan HL7v2 menggunakan tampilan RAW_ONLY, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • RAW_ONLY sebagai tampilan

Contoh berikut menunjukkan permintaan GET menggunakan PowerShell.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=RAW_ONLY" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "data": "DATA",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ]
}

Menggunakan tampilan PARSED_ONLY

Contoh berikut menunjukkan cara mendapatkan konten pesan HL7v2 menggunakan tampilan PARSED_ONLY, yang mencakup semua kolom pesan kecuali data.

curl

Untuk mendapatkan konten pesan HL7v2 menggunakan tampilan PARSED_ONLY, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • PARSED_ONLY sebagai tampilan

Contoh berikut menunjukkan permintaan GET yang menggunakan curl.

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=PARSED_ONLY"

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

PowerShell

Untuk mendapatkan konten pesan HL7v2 menggunakan tampilan PARSED_ONLY, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • PARSED_ONLY sebagai tampilan

Contoh berikut menunjukkan permintaan GET menggunakan PowerShell.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=PARSED_ONLY" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
  "sendFacility": "SEND_FACILITY",
  "sendTime": "2018-01-01T00:00:00Z",
  "messageType": "TYPE",
  "createTime": "CREATE_TIME",
  "patientIds": [
    {
        "value": "VALUE_1",
        "type": "TYPE_1"
    },
    {
        "value": "VALUE_2",
        "type": "TYPE_2"
    },
    {
        "value": "VALUE_3",
        "type": "TYPE_3"
    }
  ],
  "parsedData": {
    "segments": [
      {
        "segmentId": "SEGMENT_ID_1",
        "fields": {
          FIELDS_1
        }
      },
      {
        "segmentId": "SEGMENT_ID_2",
        "fields": {
          FIELDS_2
        }
      },
      {
        "segmentId": "SEGMENT_ID_3",
        "fields": {
          FIELDS_3
        }
      }
    ]
  }
}

Menggunakan tampilan BASIC

Contoh berikut menunjukkan cara mendapatkan konten pesan HL7v2 menggunakan tampilan BASIC, yang hanya menyertakan kolom name.

curl

Untuk mendapatkan konten pesan HL7v2 menggunakan tampilan BASIC, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • BASIC sebagai tampilan

Contoh berikut menunjukkan permintaan GET yang menggunakan curl.

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=BASIC"

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"
}

PowerShell

Untuk mendapatkan konten pesan HL7v2 menggunakan tampilan BASIC, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan
  • BASIC sebagai tampilan

Contoh berikut menunjukkan permintaan GET menggunakan PowerShell.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID?view=BASIC" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"
}

Mencantumkan pesan HL7v2

Contoh berikut menunjukkan cara mencantumkan pesan di penyimpanan HL7v2 menggunakan metode. Untuk menentukan informasi tentang setiap pesan yang akan disertakan dalam daftar, tentukan parameter kueri view dengan salah satu opsi berikut:

  • BASIC: Hanya sertakan kolom name. Ini adalah setelan defaultnya.
  • RAW_ONLY: Menyertakan semua kolom pesan kecuali kolom parsedData.
  • PARSED_ONLY: Menyertakan semua kolom pesan kecuali kolom data.
  • FULL: Menyertakan semua kolom pesan.

curl

Untuk mencantumkan pesan di penyimpanan HL7v2, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • view, salah satu dari BASIC, RAW_ONLY, PARSED_ONLY, atau FULL, atau hapus untuk menggunakan default BASIC

Contoh berikut menunjukkan permintaan GET yang menggunakan curl. Permintaan menentukan ?view=FULL untuk menyertakan semua kolom pesan.

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages?view=FULL"

Jika permintaan berhasil, server akan menampilkan kode status HTTP 200 OK dan array pesan bernama hl7_v2_messages. Contoh respons berikut dipotong.

{
  "hl7_v2_messages": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
      "data": "DATA",
      "sendFacility": "SEND_FACILITY",
      "sendTime": "SEND_TIME",
      "messageType": "MESSAGE_TYPE",
      "createTime": "CREATE_TIME",
      ...
    },
    ...
  ]
}

PowerShell

Untuk mencantumkan pesan di penyimpanan HL7v2, buat permintaan GET dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • view, salah satu dari BASIC, RAW_ONLY, PARSED_ONLY, atau FULL, atau hapus untuk menggunakan default BASIC

Contoh berikut menunjukkan permintaan GET menggunakan PowerShell. Permintaan menentukan ?view=FULL untuk menyertakan semua kolom pesan.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages?view=FULL" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan respons dalam format JSON. Contoh respons terpotong.

{
  "hl7_v2_messages": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID",
      "data": "DATA",
      "sendFacility": "SEND_FACILITY",
      "sendTime": "SEND_TIME",
      "messageType": "MESSAGE_TYPE",
      "createTime": "CREATE_TIME",
      ...
    },
    ...
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1"
)

// listHL7V2Messages prints a list of HL7V2 messages to w.
func listHL7V2Messages(w io.Writer, projectID, location, datasetID, hl7V2StoreID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s", projectID, location, datasetID, hl7V2StoreID)

	resp, err := messagesService.List(parent).Do()
	if err != nil {
		return fmt.Errorf("List: %w", err)
	}

	fmt.Fprintln(w, "HL7V2 messages:")
	for _, s := range resp.Hl7V2Messages {
		fmt.Fprintln(w, s.Name)
	}
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.ListMessagesResponse;
import com.google.api.services.healthcare.v1.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageList {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessageList(String hl7v2StoreName) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Results are paginated, so multiple queries may be required.
    String pageToken = null;

    do {
      // Create request and execute.
      ListMessagesResponse messageResponse =
          client
              .projects()
              .locations()
              .datasets()
              .hl7V2Stores()
              .messages()
              .list(hl7v2StoreName)
              .setPageSize(100)
              .setPageToken(pageToken)
              .execute();

      if (messageResponse.getHl7V2Messages() != null) {
        // Print results.
        System.out.printf(
            "Retrieved %s HL7v2 messages: \n", messageResponse.getHl7V2Messages().size());
        for (Message message : messageResponse.getHl7V2Messages()) {
          System.out.println(message);
        }
      }
      // Update the page token for the next request.
      pageToken = messageResponse.getNextPageToken();
    } while (pageToken != null);
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const listHl7v2Messages = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {parent};

  const response =
    await healthcare.projects.locations.datasets.hl7V2Stores.messages.list(
      request
    );
  const hl7v2Messages = response.data.hl7V2Messages;
  console.log(`HL7v2 messages: ${hl7v2Messages.length}`);
  for (const hl7v2Message of hl7v2Messages) {
    console.log(hl7v2Message);
  }
};

listHl7v2Messages();

Python

def list_hl7v2_messages(project_id, location, dataset_id, hl7v2_store_id):
    """Lists all the messages in the given HL7v2 store with support for
    filtering.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset ID
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    hl7v2_messages_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    hl7v2_message_path = "{}/hl7V2Stores/{}".format(
        hl7v2_messages_parent, hl7v2_store_id
    )

    hl7v2_messages = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .list(parent=hl7v2_message_path)
        .execute()
        .get("hl7V2Messages", [])
    )

    for hl7v2_message in hl7v2_messages:
        print(hl7v2_message)

    return hl7v2_messages

Menghapus pesan HL7v2

Contoh berikut menunjukkan cara menghapus pesan HL7v2 menggunakan metode projects.locations.datasets.hl7V2Stores.messages.delete.

curl

Untuk menghapus pesan HL7v2, buat permintaan DELETE dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan HL7v2

Contoh berikut menunjukkan permintaan DELETE yang menggunakan curl.

curl -X DELETE \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID"

Jika permintaan berhasil, server akan menampilkan respons isi kosong dalam format JSON:

{}

PowerShell

Untuk menghapus pesan HL7v2, buat permintaan DELETE dan tentukan informasi berikut:

  • Nama dan lokasi set data induk
  • Nama penyimpanan HL7v2
  • ID pesan HL7v2

Contoh berikut menunjukkan permintaan DELETE menggunakan PowerShell.

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Delete `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID/messages/MESSAGE_ID" | Select-Object -Expand Content

Jika permintaan berhasil, server akan menampilkan isi respons kosong dalam format JSON:

{}

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1"
)

// deleteHL7V2Message deletes an HL7V2 message.
func deleteHL7V2Message(w io.Writer, projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", err)
	}

	messagesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores.Messages

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s", projectID, location, datasetID, hl7V2StoreID, hl7V2MessageID)
	if _, err := messagesService.Delete(name).Do(); err != nil {
		return fmt.Errorf("Delete: %w", err)
	}

	fmt.Fprintf(w, "Deleted HL7V2 message: %q\n", name)
	return nil
}

Java

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores.Messages;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class HL7v2MessageDelete {
  private static final String MESSAGE_NAME =
      "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s/messages/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2MessageDelete(String hl7v2MessageName) throws IOException {
    // String hl7v2MessageName =
    //    String.format(
    //        MESSAGE_NAME, "project-id", "region-id", "dataset-id", "hl7v2-id", "message-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Create request and configure any parameters.
    Messages.Delete request =
        client.projects().locations().datasets().hl7V2Stores().messages().delete(hl7v2MessageName);

    // Execute the request and process the results.
    request.execute();
    System.out.println("HL7v2 message deleted.");
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const deleteHl7v2Message = async () => {
  // TODO(developer): uncomment the lines beginning with 'const' before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  // The value for hl7v2MessageId is the server-generated ID returned when you
  // created or ingested the HL7v2 message in an HL7v2 store.
  // const hl7v2MessageId = 'qCnewKno44gTt3oBn4dQ0u8ZA23ibDdV9GpifD2E=';
  const name = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}/messages/${hl7v2MessageId}`;
  const request = {name};

  await healthcare.projects.locations.datasets.hl7V2Stores.messages.delete(
    request
  );
  console.log('Deleted HL7v2 message');
};

deleteHl7v2Message();

Python

def delete_hl7v2_message(
    project_id, location, dataset_id, hl7v2_store_id, hl7v2_message_id
):
    """Deletes an HL7v2 message.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset ID
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    # hl7v2_message_id = '2yqbdhYHlk_ucSmWkcKOVm_N0p0OpBXgIlVG18rB-cw='  # replace with the HL7v2 message ID that was returned by the server
    hl7v2_parent = f"projects/{project_id}/locations/{location}"
    hl7v2_message = "{}/datasets/{}/hl7V2Stores/{}/messages/{}".format(
        hl7v2_parent, dataset_id, hl7v2_store_id, hl7v2_message_id
    )

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .messages()
        .delete(name=hl7v2_message)
    )

    response = request.execute()
    print(f"Deleted HL7v2 message with ID: {hl7v2_message_id}")
    return response

Langkah selanjutnya