top of page
AEnB2UrPAz1jrLwPzGy6ckjFcFP-uMXJfeyA1QYB7-97LH-694BJ06-C84AJ8mg8n-M7yi0yb50BxP5D1MphC5HNeb

TypeScript Example

This documentation provides code examples written in TypeScript, designed for integration with the WaveLight API. While WaveLight uses the React.js framework for frontend development, the provided examples can be easily adapted for any JavaScript framework or library, such as Vue.js, Angular, or even pure JavaScript (Vanilla JS).

​

Our goal is to simplify API implementation across different environments, ensuring flexibility for developers. If you prefer to use plain JavaScript, simply remove the TypeScript typings for full compatibility.​

The following documentation will guide you through using the API's key features, including file uploads, real-time event listening (SSE), and asynchronous request handling.

Service Request - Usage Example

This code example demonstrates how to create a service request for the Wavelight Health API. It includes the definition of enums, interfaces, and an asynchronous function for sending patient data and selecting services.

1. Available Services Enum

export enum Service {
  HEART_BEATS = "HEART BEATS",
  BLOOD_PRESSURE = "BLOOD PRESSURE",
  OXIMETRY = "OXIMETRY",
}

2. Patient Data Enum and Interface

export enum Gender {
  UNDEFINED = "UNDEFINED",
  MALE = "MALE",
  FEMALE = "FEMALE",
}

export interface WorkflowPerson {
  height: number;
  weight: number;
  age: number;
  gender: Gender;

}

3. API Response Interfaces

The API response contains information such as request ID, video upload URL, and structured data about the patient and study.

export interface ServiceRequestResponse {
  requestId: string;
  uploadVideoUrl: string;
  wpgContent: WpgContent;
}

​

export interface WpgContent {
  header: Header;
  study: Study;
  patient: Patient;
}

​

export interface Header {
  "content-type": string;
  version: string;
  hash: string;
  secure: boolean;
}

export interface Study {
  UUID: string;
  created: string;
  source: Source;
}

export interface Source {
  device: Device;
  institution: string;
  application: string;
  captured_by: CapturedBy;
}

export interface Device {
  model: string;
  features: string[];
}

export interface CapturedBy {
  user_type: string;
  professional_name: string;
  professional_id: string;
}

export interface Patient {
  anonymous: AnonymousField[];
}

export interface AnonymousField {
  label: "age" | "sex" | "height" | "weight" | string;
  unit: "years" | "enum" | "cm" | "kg" | string;
  value: number | string;

}

4. Function to Create a Service Request

export const createServiceRequestRequest = async (
  selectedServices: Service[],
  person: WorkflowPerson
): Promise<ServiceRequestResponse> => {
  const apiKey = ProcessingInstruction.env.API_KEY;

  const payload = {
    serviceList: selectedServices,
    WPG_Object: {
      header: {
        "content-type": "",
        version: "",
        hash: "",
        secure: true,
      },
      study: {
        created: new Date(),
        source: {
          device: {
            model: "",
            features: [],
          },
          institution: "",
          application: "",
          captured_by: {
            user_type: "",
            professional_name: "",
            professional_id: "",
          },
        },
      },
      patient: {
        anonymous: [
          { label: "age", unit: "years", value: person.age },
          { label: "sex", unit: "enum", value: person.gender },
          { label: "height", unit: "cm", value: person.height },
          { label: "weight", unit: "kg", value: person.weight },
        ],
      },
    },
  };

  const response = await axios.post<ServiceRequestResponse>(
    "https://api.wavelighthealth.com/api",
    payload,
    {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      validateStatus: () => true,
    }
  );

  return response.data;
};

5. How to Use

const personData: WorkflowPerson = {
  height: 175,
  weight: 70,
  age: 30,
  gender: Gender.MALE,
};

​

const selectedServices = [Service.HEART_BEATS, Service.BLOOD_PRESSURE];

​

createServiceRequestRequest(selectedServices, personData)
  .then(response => console.log("Service Request Created:", response))
  .catch(error => console.error("Error:", error));

uploadFileOn Function - Usage Example

The uploadFileOn function is used to upload binary files (such as videos) to an upload endpoint provided via a presigned URL. This method is commonly used for efficient file transfer to a server without passing through the developer's backend.

Parameters

  •  presigned: ServiceRequestResponse  - An object containing the presigned URL (uploadVideoUrl) where the file will be uploaded.

​​

  •  fileBlob: File  - The file to be uploaded, represented as a File object.

Implementation

export const uploadFileOn = async (
  presigned: ServiceRequestResponse,
  fileBlob: File
) => {
  const response = await axios.put(presigned.uploadVideoUrl, fileBlob, {
    headers: {
      "Content-Type": "application/octet-stream", // Ensures correct binary file upload
    },
  });

  return response.data;
};

How to Use

To use this function, follow these steps:

​

Step 1: Obtain the Presigned URL

​

Before calling   uploadFileOn , you need to obtain the presigned URL from the service API:

const serviceResponse = await createServiceRequestRequest(selectedServices, person);

Step 2: Select the File to Upload

​

The file can be obtained, for example, from an HTML input:

const fileInput = document.querySelector("input[type='file']") as HTMLInputElement;

const file = fileInput.files?.[0];

Step 3: Upload the File

​

With the presigned URL and the selected file, call  uploadFileOn 

if (file) {
  await uploadFileOn(serviceResponse, file);
  console.log("Upload successful!");
} else {
  console.error("No file selected.");
}

Considerations

  • Ensure that the presigned URL is still valid before uploading. 

  • The  Content-Type  is set to  application/octet-stream  to ensure compatibility with different binary file types.

  • This approach reduces the load on the developer's backend, as files are uploaded directly to the storage server.

Conclusion

The  uploadFileOn function provides a simple and effective solution for uploading files using presigned URLs, ensuring security and efficiency in data transmission.

listenToServiceResults Function

The  listenToServiceResults  function listens for server-sent events (SSE) related to a service request. This allows real-time updates about the processing of a request made to the API.

Parameters

The  requestId: ServiceRequestResponse function listens for server-sent events (SSE) related to a service request. This allows real-time updates about the processing of a request made to the API.

​

  •  requestId: ServiceRequestResponse  - An object containing the unique request identifier ( requestId ).

  •  selectedServices: Service[]  - List of selected services in the request.

  •  onResults: (parsedResults: any[]) => void  - Callback function called whenever new results are received.

Implementation

import { EventSourcePolyfill } from "event-source-polyfill";
export const listenToServiceResults = (
  requestId: ServiceRequestResponse,
  selectedServices: Service[],
  onResults: (parsedResults: any[]) => void
) => {
  const apiKey = process.env.API_KEY;

  const sse = new EventSourcePolyfill(
    `https://api.wavelighthealth.com/gateway/sse-request-track/${requestId.requestId}`,
    {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
    }
  );

  sse.onmessage = (event) => {
    try {
      const eventData: EventData = JSON.parse(event.data);

      if (eventData.results?.length > 0) {
        const parsedResults = eventData.results.map((result) => ({
          ...result,
          return: JSON.parse(result.return),
        }));

        onResults(parsedResults);

        const allServicesReturned = selectedServices.every((service) =>
          parsedResults.find((result) => result.name === service)
        );

        if (allServicesReturned) {
          sse.close();
        }
      }
    } catch (error) {
      console.error("[SSE] Failed to process message:", error);
    }
  };

  return sse; // Returns the SSE instance in case manual control is needed
};

How to Use

To use this function, follow these steps:

​

Step 1: Start Listening to Events

​​

After creating a service request, use the function to start listening for events:

const sse = listenToServiceResults(serviceResponse, selectedServices, (results) => {
  console.log("New results received:", results);
});

Step 2: Control the SSE Instance (Optional)

​​

If manual disconnection is needed, use:

sse.close();

Considerations

  • This approach enables real-time updates without the need for continuous polling.

  • If all services have returned a result, the connection will close automatically.

  • Ensure proper error handling to prevent execution failures.

Conclusion

The  listenToServiceResults  function provides an efficient solution for tracking server events in real time, ensuring optimized asynchronous communication between the client and service.

This documentation serves as a quick guide to integrating with the Wavelight Health API. For more information, see the official documentation.

bottom of page