CareStack EHR Node.js SDK Documentation
    Preparing search index...

    Service class responsible for generating FHIR bundles from diverse health data sources.

    This service acts as a central orchestrator for transforming both unstructured and structured clinical data into the FHIR standard format. It provides a unified entry point via create, which intelligently determines how to process the incoming request based on the data type.

    1. Unstructured Document Processing

      • When provided with URLs to clinical documents (e.g., case sheets, lab reports),
      • Uses AI-based OCR (Optical Character Recognition) and NLP (Natural Language Processing) to extract information.
      • Converts extracted insights into a structured FHIR bundle.
      • Suitable for digitizing scanned files or legacy health records.
    2. Structured Data Processing

      • Accepts direct JSON payloads matching pre-defined DTOs (e.g., OPConsultationDTO).
      • Performs validation and directly generates the FHIR bundle.
      • Ideal for systems with structured, electronic health records.

    By supporting both workflows, the EncounterService enables powerful, flexible FHIR bundle generation across varied health data inputs.

    The input DTO for encounter generation.

    A promise that resolves to the generated FHIR bundle object.

    If the input data is invalid or any transformation step fails.

    Hierarchy

    • BaseService
      • EncounterService
    Index

    Constructors

    • Parameters

      • config: ClientConfig

      Returns EncounterService

    Accessors

    Methods

    • Generates a FHIR bundle based on the provided EncounterRequestDTO.

      This method supports two modes of input:

      1. File-based: Processes files provided in the dto.caseSheets array.
      2. JSON-based: Processes JSON payload provided in dto.payload, which must match one of the supported HI types.

      If both caseSheets and payload are missing, the function throws an error.

      Parameters

      • encounterRequestDto: EncounterRequestDTO

        The DTO containing information to generate the FHIR bundle.

        • caseType: (string) The type of case. Should be one of the valid CaseType enums like OPConsultation, DischargeSummary, etc. – required
        • documentReferences: (string[]) List of base64 strings or file URLs for lab report attachments – optional
        • enableExtraction: (boolean) Flag to enable AI-based extraction of data from case sheets or Health information sections– optional
        • patientDetails: (PatientType) Details of the patient, if available – optional
        • practitionerDetails: (PractitionerType[]) List of practitioners involved in the case – optional
        • dto: (object)
          • caseSheets: (string[] | Buffer[]) Array of file data strings or Buffers for file-based processing – optional
          • payload: (object) Structured JSON payload based on one of the seven HI types – optional
            • Must conform to one of:
              • OPConsultationSections
              • DischargeSummarySections
              • PrescriptionRecordSections
              • WellnessRecordSections
              • ImmunizationRecordSections
              • DiagnosticReportSections
              • HealthDocumentRecordSections

      Returns Promise<Record<string, unknown>>

      A promise that resolves to the generated FHIR bundle object.

      Notes:

      • In both cases, if the enableExtraction flag is set to false, document references will be mandatory.
      • patientDetails and practitionerDetails are mandatory for case-2 (JSON-based processing), irrespective of the enableExtraction flag.
      • PatinetDetails and PractitionerDetails are optional for case-1 (file-based processing) if enableExtraction is set to true. If easeExtraction is false, these details are mandatory.

      If both files and payload are missing, or payload is unsupported.

      // Case-1: Generating FHIR bundle from a case sheets url/base64 string of Health Document file

      const fileData = {
      caseType: "OPConsultation",
      enableExtraction: true,
      dto: {
      caseSheets: ["base64_string_or_file_url"]
      }
      }
      const bundle = await encounter.create(fileData);
      console.log("FHIR bundle generated:", bundle);



      // Case-2: Generating FHIR bundle from a Health Information sections JSON payload

      const rawData = {
      caseType: "OPConsultation",
      enableExtraction: true,
      patientDetails: {
      "firstName": "Ravi",
      "middleName": "Kumar",
      "lastName": "Sharma",
      "birthDate": "1980-05-20",
      // ... other patient details
      },
      practitionerDetails: [{
      "firstName": "Anita",
      "middleName": "S.",
      "lastName": "Verma",
      "birthDate": "1975-08-15",
      "gender": "female",
      "mobileNumber": "+919812345678",
      // ... other practitioner details
      }],
      dto: {
      payload: {
      "chiefComplaints": "Severe headache and nausea for the past 1 day",
      "physicalExamination": {
      "bloodPressure": { "value": "140/90", "unit": "mmHg" },
      "heartRate": { "value": "88", "unit": "bpm" },
      "respiratoryRate": { "value": "18", "unit": "breaths/min" },
      "temperature": { "value": "98.7", "unit": "°F" },
      "oxygenSaturation": { "value": "97", "unit": "%" },
      "height": { "value": "160", "unit": "cm" },
      "weight": { "value": "60", "unit": "kg" }
      },
      "conditions": ["Migraine (suspected)"],
      "medicalHistory": [
      { "condition": "Hypothyroidism diagnosed 3 years ago", "procedure": "None" }
      ],
      "familyHistory": [
      {
      "relation": "Sister",
      "healthNote": "Diagnosed with migraine at age 22",
      "condition": "Migraine"
      }
      ],
      "allergies": ["No known drug allergies"],
      "immunizations": ["Tetanus booster taken 2 years ago, Lot number: TET987, Expiry: 2026-06-30"],
      "investigations": {
      "observations": {
      "serumCreatinine": { "value": "1.1", "unit": "mg/dL" },
      "sodium": { "value": "138", "unit": "mmol/L" },
      "potassium": { "value": "4.2", "unit": "mmol/L" }
      },
      "status": "preliminary",
      "recordedDate": "2024-07-12"
      },
      "prescribedMedications": [
      "Sumatriptan 50 mg – once at onset – oral – for migraine",
      "Ondansetron 4 mg – as needed – oral – for nausea"
      ],
      "currentProcedures": [
      {
      "description": "Appendectomy surgery",
      "complications": "No postoperative complications"
      }
      ],
      "advisoryNotes": [
      "Avoid bright lights and loud noises",
      "Take rest in a dark, quiet room during episodes"
      ],
      "followUp": [
      "Review after MRI report – OP-87954 – In-person"
      ]
      }
      }
      };

      const bundle = await encounter.create(rawData);
      console.log("FHIR bundle generated:", bundle);

      //Expected Output:
      FHIR bundle generated:{
      id: '7b3b5fef-7fd1-437b-940d-a55b64add446',
      meta: {
      lastUpdated: '2025-08-01T06:00:56.737721544Z',
      profile: [
      'https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle'
      ],
      security: [ [Object] ],
      versionId: '1'
      },
      identifier: {
      system: 'http://hip.in',
      value: '95328b17-adbf-49a0-b526-cd1ad8519e1c'
      },
      type: 'document',
      timestamp: '2025-08-01T06:00:56.308Z',
      entry: [
      {
      fullUrl: 'urn:uuid:43cb61d7-d59d-4935-b4ef-bd411f9e034c',
      resource: [Object]
      },
      {
      fullUrl: 'urn:uuid:37570edb-0a0d-4b6b-bc5e-c5f1ddb0853b',
      resource: [Object]
      },
      ...Other Details
      ],
      resourceType: 'Bundle'
      }
    • Checks whether a encounter exists in the system using their Resource ID.

      Parameters

      • id: string

        Unique identifier (Resource ID) of the encounter to check - mandatory

      Returns Promise<boolean>

      A promise that resolves to:

      • true if the encounter exists

      If the id is null, undefined, or an empty string.

      If the API request fails or an unexpected error occurs.

      // Input:
      const doesExist = await encounter.exists("123e4567-e89b-12d3-a456-426614174000");
      console.log(doesExist);


      // Expected Output:
      true
    • Retrieves a paginated list of all Encounters.

      Parameters

      • OptionalpageSize: number

        Number of Encounters to fetch in a single page - optional
        (Only effective in the first request. Default is 10 if not provided)

      • OptionalnextPage: string

        Cursor to fetch the next set of Encounters - optional
        (Use the value from the previous response's nextPage for pagination)

      Returns Promise<GetEncounterResponse>

      • Returns an object containing:
      • type: Type of the response (e.g., "success", "error")
      • message: Descriptive message or status of the operation
      • requestResource: Actual patient data or list of Encounters
      • totalNumberOfRecords: Total number of Encounters in the system
      • nextPageLink: Token to retrieve the next page of results, if more records exist

      Throws an error if the request fails or response is invalid.

      // Input:
      const encounters = await encounter.findAll(20);
      const moreEncounters = await encounter.findAll(undefined, encounters.nextPage);

      // Expected Output:
      {
      data: {
      Entry: [
      {
      id: 'f6fa68c6-e313-442f-bc16-ab7cddd7e052',
      resourceType: 'Encounter',
      appointmentReference: '992a77f9-897c-48b6-a852-be8e32d481ea',
      patientReference: '9a3ca20a-1bde-4e1f-b1cc-01fcd698aa42',
      practitionerReference: 'bb847118-135e-4c08-92a4-27506a3e807e',
      chiefComplaint: 'Foot pain',
      encounterType: 'ambulatory',
      // ... other fields
      },
      {
      id: 'f6fa68c6-e313-442f-bc16-ab7cddd7e052',
      resourceType: 'Encounter',
      appointmentReference: '992a77f9-897c-48b6-a852-be8e32d481ea',
      // ... other fields
      }
      // ... more entries
      ],
      link: {
      nextPage: 'X2NvdW50PTEwJl9zb3J0PS1fb'
      },
      total: 900
      }
      }
    • Fetches the details of a Encounter using Resource ID.

      Parameters

      • id: string

        Unique identifier (Resource ID) of the Encounter to fetch - mandatory

      Returns Promise<GetEncounterResponse>

      • Returns an object containing:
        • type: Type of the response (e.g., "Encounter")
        • message: Descriptive message or status of the operation
        • requestResource: Encounter data of the requested resource ID
        • totalNumberOfRecords: Total number of matched Encounter records

      If the id is null, undefined, or empty.

      If the API request fails.

      // Input:
      const encounter = await encounter.findById("123e4567-e89b-12d3-a456-426614174000");
      console.log(encounter);


      // Expected Output:
      {
      type: 'Encounter',
      message: 'Encounter Found !!!',
      requestResource: {
      //... other Details
      }
    • Parameters

      • caseType: CaseType
      • encryptedData: string

      Returns Promise<
          {
              dischargeSummary: Record<string, unknown>;
              extractedData: Record<string, unknown>;
              fhirBundle: Record<string, unknown>;
              id: string;
          },
      >

    • Parameters

      • caseType: CaseType
      • enableExtraction: boolean
      • caseSheets: string[]
      • documentReferences: string[]
      • OptionalpatientDetails: PatientType
      • OptionalpractitionerDetails: PractitionerType[]

      Returns Promise<Record<string, unknown>>