### Install Project Dependencies Source: https://github.com/tryvital/vital-node/blob/master/CONTRIBUTING.md Run this command to install all necessary project dependencies. ```bash pnpm install ``` -------------------------------- ### Install @tryvital/vital-node SDK Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/01-overview.md Install the SDK using npm or yarn. ```bash npm install @tryvital/vital-node # or yarn add @tryvital/vital-node ``` -------------------------------- ### Install Vital Node Library Source: https://github.com/tryvital/vital-node/blob/master/README.md Install the Vital Node.js library using npm or yarn. ```bash npm install --save @tryvital/vital-node # or yarn add @tryvital/vital-node ``` -------------------------------- ### client.link.startConnect Source: https://github.com/tryvital/vital-node/blob/master/reference.md Start the link token process to connect a user's account. ```APIDOC ## client.link.startConnect ### Description REQUEST_SOURCE: VITAL-LINK Start link token process. ### Parameters #### Request Body - **linkToken** (string) - Required - The link token for the connection process. - **provider** (string) - Required - The name of the provider to connect with. ### Request Example ```typescript await client.link.startConnect({ linkToken: "link_token", provider: "oura" }); ``` ``` -------------------------------- ### Getting Activity Data Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/02-VitalClient.md Demonstrates how to retrieve activity data using the `activity.get` method. It shows how to instantiate the VitalClient, access the activity client, and pass parameters such as provider, start date, end date, and request-specific options like timeout. ```APIDOC ## Getting Activity Data ### Description Retrieves activity data for a specified user within a date range from a given provider. ### Method `activity.get(userId, options, requestOptions)` ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user. #### Query Parameters - **provider** (string) - Required - The data provider (e.g., 'apple_health'). - **startDate** (string) - Required - The start date for the data range (YYYY-MM-DD). - **endDate** (string) - Required - The end date for the data range (YYYY-MM-DD). #### Request Body None ### Request Example ```typescript const vital = new VitalClient({ apiKey: 'key' }); const activityClient = vital.activity; const data = await activityClient.get('user_123', { provider: 'apple_health', startDate: '2024-01-01', endDate: '2024-01-31', }, { timeoutInSeconds: 45, }); ``` ### Response #### Success Response (200) - **data** (any) - The retrieved activity data. #### Response Example ```json { "data": [ // ... activity data objects ] } ``` ``` -------------------------------- ### Get Order Collection Instructions PDF Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Downloads the collection instructions for a specific lab order as a PDF file. ```typescript client.labTests.getOrderCollectionInstructionPdf(order_id, request?, options?) ``` -------------------------------- ### Get Order Collection Instructions PDF Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Retrieves the collection instructions for a specific order in PDF format. ```APIDOC ## GET /v3/orders/{order_id}/collection_instruction_pdf ### Description Get collection instructions for order. ### Method GET ### Endpoint /v3/orders/{order_id}/collection_instruction_pdf ### Parameters #### Path Parameters - **order_id** (string) - Required - The ID of the order. ``` -------------------------------- ### Get All Providers Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieves a list of providers. Use this to fetch available data sources. ```typescript await client.providers.getAll({ sourceType: "source_type" }); ``` -------------------------------- ### getOrderCollectionInstructionPdf Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/03-LabTestsClient.md Gets collection instructions for a specific order as a PDF. Requires an order ID. ```APIDOC ## getOrderCollectionInstructionPdf() ### Description Gets collection instructions for a specific order. ### Method GET (assumed based on retrieval) ### Endpoint /lab-tests/{order_id}/order-collection-instructions/pdf (assumed) ### Parameters #### Path Parameters - **order_id** (string) - Required - The ID of the order for which to get collection instructions. #### Request Body - **request** (Vital.LabTestsGetOrderCollectionInstructionPdfRequest) - Optional - Additional request parameters. #### Request Example ```typescript const orderInstructionsPdf = await client.labTests.getOrderCollectionInstructionPdf('order_123'); ``` ### Response #### Success Response (200) - **file** (core.BinaryResponse) - The PDF file content of the order collection instructions. ``` -------------------------------- ### Build the Project Source: https://github.com/tryvital/vital-node/blob/master/CONTRIBUTING.md Execute this command to build the project. ```bash pnpm build ``` -------------------------------- ### Get Phlebotomy Appointment Availability Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Find available phlebotomy appointment slots based on a start date and location. ```APIDOC ## Get Phlebotomy Appointment Slots ### Description Find available phlebotomy appointment slots based on a start date and address. ### Method `vital.labTests.getPhlebotomyAppointmentAvailability(options)` ### Parameters #### Query Parameters - **startDate** (string) - Required - The starting date for searching availability (YYYY-MM-DD). #### Request Body - **firstLine** (string) - Required - The first line of the address. - **city** (string) - Required - The city of the address. - **state** (string) - Required - The state of the address. - **zipCode** (string) - Required - The zip code of the address. ### Request Example ```javascript const availability = await vital.labTests.getPhlebotomyAppointmentAvailability({ startDate: '2024-02-01', body: { firstLine: '123 Main St', city: 'San Francisco', state: 'CA', zipCode: '94102', }, }); ``` ### Response #### Success Response (200) - **availability** (object) - An object containing available appointment slots. - **availableSlots** (array) - An array of available appointment slot objects. - **date** (string) - The date of the appointment slot. - **startTime** (string) - The start time of the appointment slot. - **bookingKey** (string) - A key used to book this specific slot. - **location** (object) - Information about the appointment location. - **name** (string) - The name of the location. ### Response Example ```json { "availableSlots": [ { "date": "2024-02-15", "startTime": "10:00 AM", "bookingKey": "slot_key_abc", "location": { "name": "Downtown Clinic" } } ] } ``` ``` -------------------------------- ### Get Body Measurements Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Retrieves body measurement data, such as weight and BMI, for a user starting from a specified date. ```APIDOC ## Get Body Measurements ### Description Retrieves body measurement data, including weight, BMI, and optionally body fat percentage, for a user starting from a specified date. ### Method `vital.body.get(userId, options)` ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier for the user. #### Options - **startDate** (string) - Required - The start date for the data retrieval (YYYY-MM-DD). ### Request Example ```typescript const userId = 'vital_user_abc123'; const body = await vital.body.get(userId, { startDate: '2024-01-01', }); body.data.forEach(measurement => { console.log(`${measurement.date}: Weight: ${measurement.weight} kg, BMI: ${measurement.bmi}`); }); ``` ### Response #### Success Response - **data** (array) - An array of body measurements, each containing: - **date** (string) - The date of the measurement. - **weight** (number) - The weight in kilograms. - **bmi** (number) - The Body Mass Index. - **bodyFat** (number) - Optional - The body fat percentage. ``` -------------------------------- ### Get Raw Sleep Summary - TypeScript Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve the raw sleep summary for a user. Similar to `get`, but returns raw data. Requires user ID and a request object with provider, start date, and end date. ```typescript await client.sleep.getRaw("user_id", { provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Get Phlebotomy Appointment Availability Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/03-LabTestsClient.md Retrieves available appointment slots for at-home phlebotomy. Requires a start date and address. ```typescript public getPhlebotomyAppointmentAvailability( request: Vital.LabTestsGetPhlebotomyAppointmentAvailabilityRequest, requestOptions?: LabTestsClient.RequestOptions ): core.HttpResponsePromise ``` ```typescript const slots = await client.labTests.getPhlebotomyAppointmentAvailability({ startDate: '2024-02-01', body: { firstLine: '123 Main St', city: 'San Francisco', state: 'CA', zipCode: '94102', }, }); console.log(slots.availableSlots); // Array of time slots ``` -------------------------------- ### Main Entry Point and Resource Access Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/README.md Demonstrates how to initialize the VitalClient and access various resources like user, activity, and lab tests. ```APIDOC ## Main Entry Point ### Description Initialize the VitalClient with your API key and environment, then access different resources. ### Usage ```typescript import { VitalClient, VitalEnvironment } from '@tryvital/vital-node'; const vital = new VitalClient({ apiKey: 'your_api_key', environment: VitalEnvironment.Sandbox, }); // Access resources const user = await vital.user.create({ clientUserId: 'user_123' }); const activity = await vital.activity.get(user.userId, { startDate: '2024-01-01' }); const orders = await vital.labTests.getOrders({ status: 'completed' }); ``` ### Resources Available - `vital.activity`: Activity data - `vital.aggregate`: Data aggregation queries - `vital.body`: Body measurements - `vital.devices`: Connected devices - `vital.electrocardiogram`: ECG/heart data - `vital.insurance`: Insurance verification - `vital.introspect`: Historical data discovery - `vital.labReport`: Lab reports and results - `vital.labTests`: Lab test catalog & orders - `vital.link`: Provider authentication - `vital.meal`: Nutrition data - `vital.menstrualCycle`: Menstrual cycle tracking - `vital.order`: Lab orders - `vital.payor`: Payor information - `vital.profile`: User profile - `vital.providers`: Health providers - `vital.sleep`: Sleep data - `vital.sleepCycle`: Sleep stages - `vital.team`: Team management - `vital.testkit`: Specimen kits - `vital.user`: User management - `vital.vitals`: Vital signs - `vital.workouts`: Exercise data ``` -------------------------------- ### Get Workout Data Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Retrieves workout data for a user, including type, duration, and distance, starting from a specified date. ```APIDOC ## Get Workout Data ### Description Retrieves workout records for a user, including workout type, duration, distance, and calories burned, starting from a specified date. ### Method `vital.workouts.get(userId, options)` ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier for the user. #### Options - **startDate** (string) - Required - The start date for the data retrieval (YYYY-MM-DD). - **provider** (string) - Optional - The data provider to retrieve data from (e.g., 'apple_health'). ### Request Example ```typescript const userId = 'vital_user_abc123'; const workouts = await vital.workouts.get(userId, { startDate: '2024-01-01', provider: 'apple_health', }); workouts.data.forEach(workout => { console.log(`${workout.date}: ${workout.type}, Duration: ${workout.duration / 60} minutes`); }); ``` ### Response #### Success Response - **data** (array) - An array of workout records, each containing: - **date** (string) - The date of the workout. - **type** (string) - The type of workout (e.g., 'running', 'cycling'). - **duration** (number) - The duration of the workout in seconds. - **distance** (number) - The distance covered in meters. - **calories** (number) - The number of calories burned. ``` -------------------------------- ### Get Vital Signs Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Retrieves vital signs data for a specified user. Supports filtering by provider, start date, and end date. ```typescript client.vitals.get(user_id, request, options?) ``` -------------------------------- ### Run Test Suite Source: https://github.com/tryvital/vital-node/blob/master/CONTRIBUTING.md Execute this command to run the entire test suite. ```bash pnpm test ``` -------------------------------- ### Get Vital Signs Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Retrieves vital signs data, including heart rate and blood pressure, for a user starting from a specified date. ```APIDOC ## Get Vital Signs ### Description Retrieves vital signs readings such as heart rate, blood pressure, temperature, and SpO2 for a user, starting from a specified date. ### Method `vital.vitals.get(userId, options)` ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier for the user. #### Options - **startDate** (string) - Required - The start date for the data retrieval (YYYY-MM-DD). ### Request Example ```typescript const userId = 'vital_user_abc123'; const vitals = await vital.vitals.get(userId, { startDate: '2024-01-01', }); vitals.data.forEach(reading => { console.log(`${reading.date}: Heart rate: ${reading.heartRate} bpm, BP: ${reading.systolic}/${reading.diastolic} mmHg`); }); ``` ### Response #### Success Response - **data** (array) - An array of vital sign readings, each containing: - **date** (string) - The date of the reading. - **heartRate** (number) - The heart rate in beats per minute. - **systolic** (number) - The systolic blood pressure. - **diastolic** (number) - The diastolic blood pressure. - **temperature** (number) - The body temperature in Celsius. - **oxygenSaturation** (number) - The blood oxygen saturation percentage. ``` -------------------------------- ### Initialize Vital Client and Access Resources Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/README.md Instantiate the VitalClient with your API key and environment. Then, access various resources like user, activity, and lab tests using the client instance. Ensure you replace 'your_api_key' with your actual key. ```typescript import { VitalClient, VitalEnvironment } from '@tryvital/vital-node'; const vital = new VitalClient({ apiKey: 'your_api_key', environment: VitalEnvironment.Sandbox, }); // Access resources const user = await vital.user.create({ clientUserId: 'user_123' }); const activity = await vital.activity.get(user.userId, { startDate: '2024-01-01' }); const orders = await vital.labTests.getOrders({ status: 'completed' }); ``` -------------------------------- ### Retrieve Grouped Handwashing Data Source: https://github.com/tryvital/vital-node/blob/master/reference.md Use this method to get grouped handwashing data for a user. It allows for pagination and filtering by start and end dates. ```typescript await client.vitals.handwashingGrouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Get Body Measurements Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Retrieve body measurement data, such as weight and BMI, for a user from a specified start date. Includes optional body fat percentage. ```typescript const userId = 'vital_user_abc123'; const body = await vital.body.get(userId, { startDate: '2024-01-01', }); body.data.forEach(measurement => { console.log(`${measurement.date}:`); console.log(` Weight: ${measurement.weight} kg`); console.log(` BMI: ${measurement.bmi}`); if (measurement.bodyFat) { console.log(` Body Fat: ${measurement.bodyFat}%`); } }); ``` -------------------------------- ### Initialize Vital Client (Basic) Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Instantiate the Vital client with an API key and environment. Ensure your API key is securely managed, for example, by using environment variables. ```typescript import { VitalClient, VitalEnvironment } from '@tryvital/vital-node'; const vital = new VitalClient({ apiKey: process.env.VITAL_API_KEY || 'vk_test_...', environment: VitalEnvironment.Sandbox, }); ``` -------------------------------- ### Workflow: Run Tests and Linting Source: https://github.com/tryvital/vital-node/blob/master/CONTRIBUTING.md Before committing, ensure your code passes tests and adheres to linting and formatting standards. ```bash pnpm test ``` ```bash pnpm run check:fix ``` -------------------------------- ### Retrieve Grouped Inhaler Usage Data Source: https://github.com/tryvital/vital-node/blob/master/reference.md Use this method to get grouped inhaler usage data for a user. It allows for pagination and filtering by start and end dates. ```typescript await client.vitals.inhalerUsageGrouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Get All Labs Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Fetches a list of all available labs. This endpoint is useful for discovering which labs are supported. ```typescript client.labTests.getLabs(options?) ``` -------------------------------- ### Example UsAddress Object Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/07-common-types.md Demonstrates the structure of a `UsAddress` object, which is used for shipping and other address-related information within the SDK. Ensure all required fields are provided. ```typescript const address: UsAddress = { firstLine: '123 Main St', city: 'San Francisco', state: 'CA', zipCode: '94102', }; ``` -------------------------------- ### Retrieve Grouped UV Exposure Data Source: https://github.com/tryvital/vital-node/blob/master/reference.md Use this method to get grouped UV exposure data for a user. It allows for pagination and filtering by start and end dates. ```typescript await client.vitals.uvExposureGrouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Initialize Vital Client Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/00-index.md Instantiate the main VitalClient with your API key. This is the entry point for all SDK operations. Resource clients are lazily initialized on first access. ```typescript import { VitalClient } from '@tryvital/vital-node'; const vital = new VitalClient({ apiKey: 'your_key' }); // Access resources: vital.user, vital.labTests, vital.activity, etc. ``` -------------------------------- ### Get Sleep Summary - TypeScript Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve a user's sleep summary. Requires user ID and a request object with provider, start date, and end date. ```typescript await client.sleep.get("user_id", { provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Complete Vital Client Configuration Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/04-configuration.md Configure the Vital Node client with API key, environment, networking options, custom headers, and logging. This example also shows how to override settings for a specific request. ```typescript import { VitalClient, VitalEnvironment } from '@tryvital/vital-node'; const client = new VitalClient({ // Authentication apiKey: process.env.VITAL_API_KEY || 'vk_test_...', // Environment environment: VitalEnvironment.Sandbox, // Networking timeoutInSeconds: 45, maxRetries: 3, // Custom headers headers: { 'X-Request-Context': 'myapp/v1', 'X-Client-ID': process.env.CLIENT_ID, }, // Logging logging: { level: 'debug' }, }); // Per-request override const result = await client.labTests.get( { status: 'active' }, { timeoutInSeconds: 120, maxRetries: 5, headers: { 'X-Request-ID': crypto.randomUUID(), }, } ); ``` -------------------------------- ### Get Workout Data Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Retrieve workout session details for a user, including type, duration, distance, and calories burned. Specify the provider and start date for filtering. ```typescript const userId = 'vital_user_abc123'; const workouts = await vital.workouts.get(userId, { startDate: '2024-01-01', provider: 'apple_health', }); workouts.data.forEach(workout => { const durationMin = workout.duration / 60; console.log(`${workout.date}: ${workout.type}`); console.log(` Duration: ${durationMin} minutes`); console.log(` Distance: ${workout.distance} meters`); console.log(` Calories: ${workout.calories}`); }); ``` -------------------------------- ### Start Link Token Process Source: https://github.com/tryvital/vital-node/blob/master/reference.md Initiates the link token process for a specific provider. This is part of the user connection flow. ```typescript await client.link.startConnect({ linkToken: "link_token", provider: "oura" }); ``` -------------------------------- ### Get User Activity Summary Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieves a summary of a user's activity. Requires user ID and optional parameters like provider, start date, and end date. ```typescript await client.activity.get("user_id", { provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Get Vital Signs Data Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Retrieve vital signs readings, such as heart rate and blood pressure, for a user starting from a specified date. Data is fetched from connected providers. ```typescript const userId = 'vital_user_abc123'; const vitals = await vital.vitals.get(userId, { startDate: '2024-01-01', }); vitals.data.forEach(reading => { console.log(`${reading.date}:`); console.log(` Heart rate: ${reading.heartRate} bpm`); console.log(` BP: ${reading.systolic}/${reading.diastolic} mmHg`); console.log(` Temperature: ${reading.temperature}°C`); console.log(` SpO2: ${reading.oxygenSaturation}%`); }); ``` -------------------------------- ### Configure Vital Client for Sandbox Environment Source: https://github.com/tryvital/vital-node/blob/master/README.md Initialize the Vital client to use the Sandbox environment by specifying the 'environment' option. Replace 'YOUR_API_KEY' with your actual key. ```typescript import { VitalClient, VitalEnvironment } from '@tryvital/vital-node'; const vital = new VitalClient({ apiKey: 'YOUR_API_KEY', environmment: VitalEnvironment.Sandbox, }); ``` -------------------------------- ### POST /v2/user Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Create a new user in the system. ```APIDOC ## POST /v2/user ### Description Create a new user. ### Method POST ### Endpoint /v2/user ### Parameters #### Request Body - **clientUserId** (string) - Required - The unique identifier for the client user. ### Response #### Success Response (200) - **ClientFacingUserKey** (object) - Response containing the key for the newly created user ``` -------------------------------- ### Get User Body Summary Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve a summary of a user's body data. Requires user ID and request parameters including provider, start date, and end date. ```typescript await client.body.get("user_id", { provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### client.link.connectDemoProvider Source: https://github.com/tryvital/vital-node/blob/master/reference.md Connects the given Vital user to a demo provider. ```APIDOC ## client.link.connectDemoProvider ### Description POST Connect the given Vital user to a demo provider. ### Method POST ### Endpoint /link/connectDemoProvider ### Parameters #### Request Body - **request** (Vital.DemoConnectionCreationPayload) - Required - The request body containing demo connection details. - **requestOptions** (LinkClient.RequestOptions) - Optional - Additional request options. ### Request Example ```typescript await client.link.connectDemoProvider({ userId: "user_id", provider: "apple_health_kit" }); ``` ### Response #### Success Response (200) - **Vital.DemoConnectionStatus** - The status of the demo connection. #### Response Example ```json { "example": "Vital.DemoConnectionStatus" } ``` ``` -------------------------------- ### Get PSC Appointment Availability Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve available appointment slots for a PSC (Patient Service Center). Requires lab identifier, start date, and zip code. A radius can also be specified. ```typescript await client.labTests.getPscAppointmentAvailability({ lab: "quest", startDate: "start_date", zipCode: "zip_code", radius: "10" }); ``` -------------------------------- ### Handling Lazy Initialization Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/02-VitalClient.md Illustrates the lazy initialization of client instances. The first time a property like `labTests` is accessed, its corresponding client is created and cached. Subsequent accesses return the same cached instance, ensuring efficiency. ```APIDOC ## Handling Lazy Initialization ### Description Demonstrates that client instances are lazily initialized and cached upon first access. Subsequent accesses to the same client property will return the cached instance. ### Method Accessing client properties (e.g., `vital.labTests`) ### Example ```typescript const vital = new VitalClient({ apiKey: 'key' }); // First access: creates and caches LabTestsClient const client1 = vital.labTests; // Subsequent access: returns the cached instance const client2 = vital.labTests; console.log(client1 === client2); // true ``` ``` -------------------------------- ### Get Phlebotomy Appointment Slots Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Find available phlebotomy appointment slots for a given order, based on a start date and a user's address. Useful for scheduling in-person blood draws. ```typescript const orderId = 'order_123'; const availability = await vital.labTests.getPhlebotomyAppointmentAvailability({ startDate: '2024-02-01', body: { firstLine: '123 Main St', city: 'San Francisco', state: 'CA', zipCode: '94102', }, }); console.log(`Available slots: ${availability.availableSlots.length}`); availability.availableSlots.slice(0, 3).forEach(slot => { console.log(`${slot.date} at ${slot.startTime}`); console.log(` Location: ${slot.location.name}`); }); ``` -------------------------------- ### client.labTests.create Source: https://github.com/tryvital/vital-node/blob/master/reference.md Creates a new lab test. Requires name, method, and description. ```APIDOC ## Create Lab Test ### Description Creates a new lab test. ### Method POST ### Endpoint /lab-tests ### Parameters #### Request Body - **name** (string) - Required - The name of the lab test. - **method** (string) - Required - The collection method for the lab test (e.g., 'testkit'). - **description** (string) - Optional - A description of the lab test. ### Request Example ```typescript await client.labTests.create({ name: "name", method: "testkit", description: "description" }); ``` ### Response #### Success Response (200) - **Vital.ClientFacingLabTest** - The newly created lab test object. ``` -------------------------------- ### Get Activity Data Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/02-VitalClient.md Fetch activity data for a specific user within a date range. Requires an initialized VitalClient and specifies provider, start date, and end date. Allows overriding the default request timeout. ```typescript const vital = new VitalClient({ apiKey: 'key' }); // Access cached or new ActivityClient instance const activityClient = vital.activity; const data = await activityClient.get('user_123', { provider: 'apple_health', startDate: '2024-01-01', endDate: '2024-01-31', }, { timeoutInSeconds: 45, }); ``` -------------------------------- ### Get Grouped Wheelchair Push - Vital Node Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve grouped wheelchair push data for a specific user. Requires user ID and request parameters including optional cursor, provider, start date, and end date. ```typescript await client.vitals.wheelchairPushGrouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Initialize VitalClient Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/01-overview.md Initialize the VitalClient with your API key and environment. Use VitalEnvironment.Sandbox for testing. ```typescript import { VitalClient, VitalEnvironment } from '@tryvital/vital-node'; const vital = new VitalClient({ apiKey: 'YOUR_API_KEY', environment: VitalEnvironment.Sandbox, }); ``` -------------------------------- ### Get Grouped Sleep Apnea Alert - Vital Node Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve grouped sleep apnea alert data for a specific user. Requires user ID and request parameters including optional cursor, provider, start date, and end date. ```typescript await client.vitals.sleepApneaAlertGrouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### client.user.create Source: https://github.com/tryvital/vital-node/blob/master/reference.md POST Create a Vital user given a client_user_id and returns the user_id. ```APIDOC ## client.user.create ### Description POST Create a Vital user given a client_user_id and returns the user_id. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **clientUserId** (string) - Required - The unique identifier for the user on the client side. ### Request Example ```typescript await client.user.create({ clientUserId: "client_user_id" }); ``` ### Response #### Success Response (201) - **userId** (string) - The unique identifier for the newly created Vital user. ``` -------------------------------- ### Get Grouped Sleep Breathing Disturbance - Vital Node Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve grouped sleep breathing disturbance data for a specific user. Requires user ID and request parameters including optional cursor, provider, start date, and end date. ```typescript await client.vitals.sleepBreathingDisturbanceGrouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Initialize Vital Client and Fetch Lab Test Source: https://github.com/tryvital/vital-node/blob/master/README.md Initialize the Vital client with an API key and fetch a lab test by its order ID. Ensure you replace 'YOUR_API_KEY' with your actual key. ```typescript import { VitalClient, VitalEnvironment } from '@tryvital/vital-node'; const vital = new VitalClient({ apiKey: 'YOUR_API_KEY', }); const labTest = await vital.labTests.get('order-id'); console.log('Received lab test', labTest); ``` -------------------------------- ### Get Grouped Forced Vital Capacity - Vital Node Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve grouped forced vital capacity data for a specific user. Requires user ID and request parameters including optional cursor, provider, start date, and end date. ```typescript await client.vitals.forcedVitalCapacityGrouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Initialize Vital Client (Multiple Environments) Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Create a factory function to easily instantiate Vital clients for different environments (e.g., sandbox and production). This promotes code reusability and environment consistency. ```typescript const createClient = (env: string) => { return new VitalClient({ apiKey: process.env.VITAL_API_KEY, environment: env === 'production' ? VitalEnvironment.Production : VitalEnvironment.Sandbox, }); }; const sandboxClient = createClient('sandbox'); const prodClient = createClient('production'); ``` -------------------------------- ### Configure Vital Client with Environment Variables Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/04-configuration.md Set API keys, environments, and timeouts using environment variables for flexible SDK configuration. Fallbacks to default values are provided. ```typescript const vital = new VitalClient({ apiKey: process.env.VITAL_API_KEY || 'default_key', environment: (process.env.VITAL_ENV as VitalEnvironment) || VitalEnvironment.Production, timeoutInSeconds: parseInt(process.env.VITAL_TIMEOUT || '60'), }); ``` -------------------------------- ### Access Validation Error Details Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/05-errors.md When a 422 Unprocessable Entity error occurs, access the 'detail' property of the error body to get specific validation failure information. This example shows how to iterate through validation errors and log field paths and messages. ```typescript interface ValidationError { detail: Array<{ type: string; // "value_error", "type_error", etc. loc: string[]; // ["body", "fieldName"] or ["query", "param"] msg: string; // Human-readable error message input?: unknown; // The value that failed validation ctx?: Record; // Additional context }>; } ``` ```typescript import { Vital } from '@tryvital/vital-node'; try { await client.labTests.getOrders({ startDate: new Date('invalid'), }); } catch (error) { if (error instanceof Vital.UnprocessableEntityError) { const validationErrors = error.body as { detail: Array<{ type: string; loc: string[]; msg: string; }>; }; validationErrors.detail.forEach(detail => { const fieldPath = detail.loc.join('.'); console.log(`${fieldPath}: ${detail.msg} (${detail.type})`); }); } } ``` -------------------------------- ### Get Grouped Peak Expiratory Flow Rate - Vital Node Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve grouped peak expiratory flow rate data for a specific user. Requires user ID and request parameters including optional cursor, provider, start date, and end date. ```typescript await client.vitals.peakExpiratoryFlowRateGrouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### Pagination for List Resources Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/06-resources.md Demonstrates how to paginate through resources that return lists of items. Use 'offset' and 'limit' parameters to control the data subset retrieved. ```typescript const users = await client.user.getAll({ offset: 0, limit: 50, }); const nextPage = await client.user.getAll({ offset: 50, limit: 50, }); ``` -------------------------------- ### Get Grouped Forced Expiratory Volume 1 - Vital Node Source: https://github.com/tryvital/vital-node/blob/master/reference.md Retrieve grouped forced expiratory volume in 1 second data for a specific user. Requires user ID and request parameters including optional cursor, provider, start date, and end date. ```typescript await client.vitals.forcedExpiratoryVolume1Grouped("user_id", { cursor: "cursor", nextCursor: "next_cursor", provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### VitalClient Initialization with Predefined Environment Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/04-configuration.md Configure the client to target a specific predefined API environment like Sandbox. ```typescript const client = new VitalClient({ apiKey: 'key', environment: VitalEnvironment.Sandbox, }); ``` -------------------------------- ### Get Order Collection Instructions PDF Source: https://github.com/tryvital/vital-node/blob/master/reference.md Fetch the PDF document containing collection instructions for a given order ID. ```typescript await client.labTests.getOrderCollectionInstructionPdf("order_id"); ``` -------------------------------- ### Configure Client with Debug Logging Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/04-configuration.md Enable debug logging by setting the 'level' to 'debug' in the client's logging configuration. ```typescript const client = new VitalClient({ apiKey: 'key', logging: { level: 'debug' }, }); ``` -------------------------------- ### Check Code Style Source: https://github.com/tryvital/vital-node/blob/master/CONTRIBUTING.md Run these commands to check the code style and formatting without making changes. ```bash pnpm run lint ``` ```bash pnpm run format:check ``` -------------------------------- ### GET /v2/summary/sleep/{user_id} Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Get a summary of a user's sleep data within a specified date range. ```APIDOC ## GET /v2/summary/sleep/{user_id} ### Description Get sleep summary. ### Method GET ### Endpoint /v2/summary/sleep/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. #### Query Parameters - **provider** (string) - Optional - Filter by provider - **start_date** (string) - Optional - Start date (ISO 8601) - **end_date** (string) - Optional - End date (ISO 8601) ### Response #### Success Response (200) - **SleepResponse** (object) - Response containing the user's sleep summary ``` -------------------------------- ### Environments Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/00-index.md The Vital SDK supports multiple environments, allowing you to target different deployment regions and stages (production or sandbox). ```APIDOC ## Environments Four environments available: ```typescript VitalEnvironment.Production // https://api.tryvital.io VitalEnvironment.ProductionEu // https://api.eu.tryvital.io VitalEnvironment.Sandbox // https://api.sandbox.tryvital.io VitalEnvironment.SandboxEu // https://api.sandbox.eu.tryvital.io ``` Default: Production ``` -------------------------------- ### GET /v2/summary/activity/{user_id} Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Get a summary of a user's activity data within a specified date range. ```APIDOC ## GET /v2/summary/activity/{user_id} ### Description Get activity summary. ### Method GET ### Endpoint /v2/summary/activity/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. #### Query Parameters - **provider** (string) - Optional - Filter by provider - **start_date** (string) - Optional - Start date (ISO 8601) - **end_date** (string) - Optional - End date (ISO 8601) ### Response #### Success Response (200) - **ClientActivityResponse** (object) - Response containing the user's activity summary ``` -------------------------------- ### Handle Lazy Initialization of Clients Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/02-VitalClient.md Demonstrates how client instances are lazily initialized and cached upon first access. Subsequent accesses to the same client property return the cached instance, ensuring efficiency. ```typescript const vital = new VitalClient({ apiKey: 'key' }); // First access: creates LabTestsClient const client1 = vital.labTests; // Subsequent accesses: returns cached instance const client2 = vital.labTests; console.log(client1 === client2); // true ``` -------------------------------- ### Get Raw User Activity Data Source: https://github.com/tryvital/vital-node/blob/master/reference.md Fetches the raw activity data for a user. Similar to getting a summary, but provides unprocessed activity details. Requires user ID and date range parameters. ```typescript await client.activity.getRaw("user_id", { provider: "provider", startDate: "start_date", endDate: "end_date" }); ``` -------------------------------- ### User Client Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/06-resources.md Manage users in your Vital workspace. ```APIDOC ## User Client **Access**: `client.user` Manage users in your Vital workspace. ### Methods #### List all users - **Method**: `getAll` - **Parameters**: - `request` (UserGetAllRequest) - Optional - `offset` (number) - Optional - `limit` (number) - Optional - `requestOptions` (RequestOptions) - Optional - **Returns**: `Promise` #### Create a new user - **Method**: `create` - **Parameters**: - `request` (UserCreateBody) - Required - `clientUserId` (string) - Yes - Your internal user identifier - `requestOptions` (RequestOptions) - Optional - **Returns**: `Promise` #### Get specific user - **Method**: `getUser` - **Parameters**: - `userId` (string) - Required - `requestOptions` (RequestOptions) - Optional - **Returns**: `Promise` #### Delete a user - **Method**: `delete` - **Parameters**: - `userId` (string) - Required - `requestOptions` (RequestOptions) - Optional - **Returns**: `Promise` #### Deactivate a user - **Method**: `deactivate` - **Parameters**: - `userId` (string) - Required - `requestOptions` (RequestOptions) - Optional - **Returns**: `Promise` ### Example ```typescript // Create new user const user = await client.user.create({ clientUserId: 'internal_user_123', }); console.log(user.userId); // Vital user ID console.log(user.clientUserId); // Your ID // List users with pagination const users = await client.user.getAll({ offset: 0, limit: 50, }); users.data.forEach(u => { console.log(u.userId, u.clientUserId); }); ``` ``` -------------------------------- ### Check Order Status and Get Results Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Retrieve the status of a lab order and, if results are available, fetch them in raw format, download as PDF, or get metadata. Essential for tracking and accessing patient results. ```typescript const orderId = 'order_123'; // Check order status const order = await vital.labTests.getOrder(orderId); console.log(`Order status: ${order.status}`); if (order.resultsAvailable) { // Get results const results = await vital.labTests.getResultRaw(orderId); console.log('Results:', results.data); // Download results PDF const pdf = await vital.labTests.getResultPdf(orderId); // Save to file, send to email, etc. // Get metadata about results const metadata = await vital.labTests.getResultMetadata(orderId); console.log(`Result date: ${metadata.resultDate}`); console.log(`Lab: ${metadata.labName}`); } ``` -------------------------------- ### Initialize Vital Client (Custom Configuration) Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Configure the Vital client with advanced options like custom timeouts, retry counts, headers, and logging levels. Useful for fine-tuning SDK behavior. ```typescript const vital = new VitalClient({ apiKey: 'vk_live_...', environment: VitalEnvironment.Production, timeoutInSeconds: 45, maxRetries: 3, headers: { 'X-App-Version': '1.0.0', 'X-Request-Context': 'backend-service', }, logging: { level: 'debug' }, }); ``` -------------------------------- ### Get All Labs Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Retrieves a list of all available labs. ```APIDOC ## GET /v3/lab_tests/labs ### Description Get all available labs. ### Method GET ### Endpoint /v3/lab_tests/labs ### Response #### Success Response (200) - **Response**: `ClientFacingLab[]` ``` -------------------------------- ### GET /v2/user/{user_id} Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Retrieve details for a specific user. ```APIDOC ## GET /v2/user/{user_id} ### Description Get user details. ### Method GET ### Endpoint /v2/user/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **ClientFacingUser** (object) - Response containing the user's details ``` -------------------------------- ### VitalClient Constructor Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/02-VitalClient.md Initializes the VitalClient with optional configuration options. ```APIDOC ## Constructor ```typescript constructor(options?: VitalClient.Options) ``` ### Description Initializes the VitalClient with optional configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (VitalClient.Options) - Optional - Configuration object for the client. - **apiKey** (string) - Required - API key for authentication. - **environment** (VitalEnvironment | string) - Optional - Target environment/URL. Defaults to Production. - **baseUrl** (string | Supplier) - Optional - Custom base URL. - **timeoutInSeconds** (number) - Optional - Default request timeout. Defaults to 60. - **maxRetries** (number) - Optional - Default retry count. Defaults to 2. - **headers** (Record>) - Optional - Additional default headers. - **fetch** (typeof fetch) - Optional - Custom fetch implementation. - **logging** (LogConfig | Logger) - Optional - Logging configuration. ### Request Example ```typescript import { VitalClient, VitalEnvironment } from '@tryvital/vital-node'; const vital = new VitalClient({ apiKey: 'your_api_key', environment: VitalEnvironment.Sandbox, timeoutInSeconds: 30, maxRetries: 3, }); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Lab Test Collection Instructions PDF Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Downloads the collection instructions for a specific lab test as a PDF file. ```typescript client.labTests.getLabTestCollectionInstructionPdf(lab_test_id, options?) ``` -------------------------------- ### GET /v2/user Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md List all users in the team. Supports pagination. ```APIDOC ## GET /v2/user ### Description List all users in team. Supports pagination. ### Method GET ### Endpoint /v2/user ### Parameters #### Query Parameters - **offset** (number) - Optional - Pagination offset - **limit** (number) - Optional - Page size ### Response #### Success Response (200) - **PaginatedUsersResponse** (object) - Response containing a paginated list of users ``` -------------------------------- ### Get All Markers Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/08-api-endpoints.md Retrieves a list of all markers, with support for filtering. ```APIDOC ## GET /v3/lab_tests/markers ### Description Get all markers with filtering. ### Method GET ### Endpoint /v3/lab_tests/markers ### Parameters #### Query Parameters - **labId** (number[]) - Optional - lab_id - **name** (string) - Optional - name - **aLaCarteEnabled** (boolean) - Optional - a_la_carte_enabled - **labAccountId** (string) - Optional - lab_account_id - **page** (number) - Optional - page - **size** (number) - Optional - size ### Response #### Success Response (200) - **Response**: `GetMarkersResponse` ``` -------------------------------- ### Bulk User Creation with Vital Node Source: https://github.com/tryvital/vital-node/blob/master/_autodocs/09-examples.md Create multiple users concurrently using Promise.all. Includes error handling for individual user creation failures. ```typescript const userIds = ['user_1', 'user_2', 'user_3']; const createdUsers = Promise.all( userIds.map(id => vital.user.create({ clientUserId: id }) .catch(error => { console.error(`Failed to create ${id}:`, error); return null; }) ) ); const successCount = createdUsers.filter(Boolean).length; console.log(`Created ${successCount}/${userIds.length} users`); ``` -------------------------------- ### Get Lab Test Area Information Source: https://github.com/tryvital/vital-node/blob/master/reference.md Use this to get information about a specific area for lab testing, including network serviceability for a zip code and a list of lab locations. Requires zip code, radius, lab name, and optionally a lab account ID. ```typescript await client.labTests.getAreaInfo({ zipCode: "zip_code", radius: "10", lab: "quest", labAccountId: "lab_account_id" }); ```