### Configure Google Analytics with dataLayer (JavaScript) Source: https://github.com/beda-software/fhir-emr/blob/master/public/index.production.html This snippet initializes the Google Analytics tracking for the Beda EMR application. It ensures the dataLayer is ready and sends the initial configuration to Google Analytics. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'AW-11071319885'); ``` -------------------------------- ### Authentication Service: Login, Logout, and Token Management Source: https://context7.com/beda-software/fhir-emr/llms.txt Handles user authentication, including password-based login and OAuth flows. Manages session tokens and provides functions for getting user info, generating authorization URLs, and exchanging codes for tokens. Requires the '@beda.software/emr/services' library. ```typescript import { login, logout, doLogout, getUserInfo, getToken, setToken, removeToken, getAuthorizeUrl, exchangeAuthorizationCodeForToken, signinWithIdentityToken, } from '@beda.software/emr/services'; // Password-based login const loginResult = await login({ email: 'doctor@hospital.com', password: 'secure-password-123', }); if (isSuccess(loginResult)) { setToken(loginResult.data.access_token); console.log('User:', loginResult.data.userinfo); } // Get current user information const userInfoResult = await getUserInfo(); if (isSuccess(userInfoResult)) { console.log('Current user:', userInfoResult.data); } // OAuth authorization URL generation const authUrl = getAuthorizeUrl({ authPath: 'auth/authorize', params: new URLSearchParams({ client_id: 'emr-client', redirect_uri: 'https://emr.example.com/callback', response_type: 'code', scope: 'openid profile', }), state: { nextUrl: '/dashboard' }, }); // Exchange authorization code for tokens const tokenResult = await exchangeAuthorizationCodeForToken(authorizationCode); if (isSuccess(tokenResult)) { setToken(tokenResult.data.access_token); } // Complete logout (clears session and tokens) await doLogout(); // Redirects to '/' ``` -------------------------------- ### FHIR Service API: CRUD and Search Operations Source: https://context7.com/beda-software/fhir-emr/llms.txt Provides functions for interacting with FHIR resources via the Aidbox backend. Supports typed CRUD operations (get, create, update, delete, patch) and searching for resources. Requires the '@beda.software/emr/services' library and FHIR resource types from 'fhir/r4b'. ```typescript import { getFHIRResource, getFHIRResources, createFHIRResource, updateFHIRResource, saveFHIRResource, deleteFHIRResource, patchFHIRResource, service, setInstanceToken, resetInstanceToken, } from '@beda.software/emr/services'; import { Patient, Appointment, Bundle } from 'fhir/r4b'; // Get a single FHIR resource by reference const patientResult = await getFHIRResource({ reference: 'Patient/patient-123', }); if (isSuccess(patientResult)) { console.log('Patient:', patientResult.data.name); } // Search for FHIR resources with parameters const appointmentsResult = await getFHIRResources('Appointment', { patient: 'Patient/patient-123', status: 'booked', _sort: '-date', _count: 10, }); // Create a new FHIR resource const newPatient: Patient = { resourceType: 'Patient', name: [{ given: ['John'], family: 'Doe' }], birthDate: '1990-01-15', gender: 'male', }; const createResult = await createFHIRResource(newPatient); // Update an existing resource (full replacement) const updateResult = await updateFHIRResource( { ...existingPatient, active: true }, { id: 'patient-123' } ); // Patch a resource (partial update) const patchResult = await patchFHIRResource({ id: 'patient-123', resourceType: 'Patient', active: false, }); // Generic service call for custom operations const customResult = await service({ method: 'POST', url: '/Questionnaire/$populate', data: parametersResource, }); ``` -------------------------------- ### Manage Cloud File Uploads and Downloads (TypeScript) Source: https://context7.com/beda-software/fhir-emr/llms.txt This service facilitates secure file uploads and downloads to cloud storage by generating presigned URLs. It includes functions for generating upload/download URLs, retrieving download headers for authenticated fetches, and uploading files using XHR with progress tracking. Dependencies include '@beda.software/remote-data' for handling results. ```typescript import { generateUploadUrl, generateDownloadUrl, generateDownloadHeaders, uploadFileWithXHR, } from '@beda.software/emr/services'; import { isSuccess } from '@beda.software/remote-data'; // Generate presigned upload URL and upload file async function uploadDocument(file: File) { const uploadResult = await generateUploadUrl(file.name); if (isSuccess(uploadResult)) { const { filename, uploadUrl } = uploadResult.data; // Upload using XHR with progress tracking uploadFileWithXHR( { file, onProgress: ({ percent }) => { console.log(`Upload progress: ${percent}%`); }, onSuccess: () => { console.log('Upload complete, key:', filename); }, onError: (error) => { console.error('Upload failed:', error); }, }, uploadUrl ); return filename; // Store this key for later retrieval } } // Generate download URL for stored file async function downloadDocument(fileKey: string) { const downloadResult = await generateDownloadUrl(fileKey); if (isSuccess(downloadResult)) { window.open(downloadResult.data.downloadUrl, '_blank'); } } // Get download headers for authenticated fetch async function fetchDocumentWithHeaders(fileKey: string) { const headersResult = await generateDownloadHeaders(fileKey); if (isSuccess(headersResult)) { const response = await fetch(fileUrl, { headers: headersResult.data, }); return response.blob(); } } ``` -------------------------------- ### Manage User Roles and Resource Access Source: https://context7.com/beda-software/fhir-emr/llms.txt Utilities for handling role-based access control and selecting resources based on the current user's role. Depends on '@beda.software/emr/utils' and '@beda.software/aidbox-types'. Enables dynamic UI rendering and resource retrieval based on user roles. ```typescript import { Role, selectUserRole, matchCurrentUserRole, selectCurrentUserRoleResource, } from '@beda.software/emr/utils'; import { User } from '@beda.software/aidbox-types'; // Select value based on user role function getHomePage(user: User): string { return selectUserRole(user, { [Role.Patient]: '/my-records', [Role.Admin]: '/admin/dashboard', [Role.Practitioner]: '/patients', [Role.Receptionist]: '/appointments', }); } // Match current user role with typed callbacks function getCurrentUserDashboard() { return matchCurrentUserRole({ [Role.Patient]: (patient) => , [Role.Admin]: (organization) => , [Role.Practitioner]: (practitioner) => , [Role.Receptionist]: (practitioner) => , }); } // Get the current user's associated FHIR resource function getAuthorReference() { const resource = selectCurrentUserRoleResource(); return { reference: `${resource.resourceType}/${resource.id}`, display: resource.resourceType === 'Patient' ? renderHumanName(resource.name?.[0]) : resource.resourceType === 'Organization' ? resource.name : renderHumanName(resource.name?.[0]), }; } ``` -------------------------------- ### Render FHIR Questionnaire Forms with BaseQuestionnaireResponseForm Component (TypeScript) Source: https://context7.com/beda-software/fhir-emr/llms.txt The `BaseQuestionnaireResponseForm` component renders FHIR Questionnaire forms with full SDC support. It handles validation, custom widgets, and wizard navigation. It accepts form data, submission handlers, save draft handlers, and configuration for custom validation and item controls. Dependencies include `@beda.software/emr/components` and `sdc-qrf`. ```typescript import { BaseQuestionnaireResponseForm } from '@beda.software/emr/components'; import { QuestionnaireResponseFormData } from 'sdc-qrf'; interface MyFormProps { formData: QuestionnaireResponseFormData; onComplete: () => void; } function MyForm({ formData, onComplete }: MyFormProps) { const handleSubmit = async (data: QuestionnaireResponseFormData) => { const result = await saveQuestionnaireResponse(data); if (isSuccess(result)) { onComplete(); } }; const handleSaveDraft = async (qr: QuestionnaireResponse) => { return await saveFHIRResource({ ...qr, status: 'in-progress' }); }; return ( navigate(-1)} readOnly={false} // Custom validation tests customYupTests={{ 'phone-input': [{ name: 'valid-phone', test: (value) => /^\+?[1-9]\d{9,14}$/.test(value), message: 'Invalid phone number format', }], }} // Custom item control components itemControlQuestionItemComponents={{ 'custom-slider': CustomSliderWidget, 'file-upload': FileUploadWidget, }} itemControlGroupItemComponents={{ 'collapsible-group': CollapsibleGroupWidget, }} // Track form changes onQRFUpdate={(qr) => { console.log('Form updated:', qr); }} /> ); } ``` -------------------------------- ### Expand FHIR ValueSets using Services (TypeScript) Source: https://context7.com/beda-software/fhir-emr/llms.txt This service provides functions to expand FHIR ValueSets, supporting local, predefined lists, and external terminology servers. It takes a ValueSet identifier and an optional search term or configuration. The output is a list of coding options. ```typescript import { expandFHIRValueSet, expandValueSet, expandEMRValueSet, expandHealthSamuraiValueSet, expandExternalTerminology, } from '@beda.software/emr/services'; // Expand a local FHIR ValueSet const options = await expandFHIRValueSet( 'http://hl7.org/fhir/ValueSet/administrative-gender', 'mal' // search filter ); // Returns: [{ value: { Coding: { code: 'male', system: '...', display: 'Male' } } }] // Expand with predefined ValueSet list (uses Health Samurai terminology server) const relationshipOptions = await expandValueSet({ answerValueSet: 'http://hl7.org/fhir/ValueSet/relatedperson-relationshiptype', searchText: 'parent', predefinedValueSetsList: ['relatedperson-relationshiptype'], }); // Expand from external terminology server const snomedOptions = await expandExternalTerminology( 'https://tx.fhir.org/r4', 'http://snomed.info/sct?fhir_vs=isa/404684003', 'diabetes' ); // EMR-specific expansion with fallback const medicationOptions = await expandEMRValueSet( 'http://hl7.org/fhir/ValueSet/medicationknowledge-package-type', 'bottle', 'https://custom-terminology.server.com' // optional external server ); ``` -------------------------------- ### Display FHIR Resources with ResourceTable Component (TypeScript) Source: https://context7.com/beda-software/fhir-emr/llms.txt The ResourceTable component renders FHIR resources in a paginated and sortable table. It supports automatic data fetching and provenance tracking. Dependencies include Ant Design for tables and FHIR R4B types. It takes resource type, query parameters, and column definitions as input. ```typescript import { ResourceTable, useResourceTable } from '@beda.software/emr/components'; import { Patient, Provenance } from 'fhir/r4b'; import { ColumnsType } from 'antd/es/table'; // Define table columns with provenance support const getPatientColumns = (provenanceList: Provenance[]): ColumnsType => [ { title: 'Name', dataIndex: 'name', render: (_, patient) => renderHumanName(patient.name?.[0]), }, { title: 'Birth Date', dataIndex: 'birthDate', render: (date) => formatHumanDate(date), }, { title: 'Gender', dataIndex: 'gender', }, { title: 'Last Updated', render: (_, patient) => { const provenance = provenanceList.find( (p) => p.target?.[0]?.reference === `Patient/${patient.id}` ); return provenance?.recorded ? formatHumanDateTime(provenance.recorded) : '-'; }, }, ]; // Basic usage function PatientList() { return ( resourceType="Patient" params={{ active: true, _revinclude: ['Provenance:target'], }} getTableColumns={getPatientColumns} /> ); } // Using the hook for custom rendering function CustomPatientList() { const { response, pagination, handleTableChange } = useResourceTable({ resourceType: 'Patient', params: { active: true }, }); return ( {(bundle) => { const patients = extractBundleResources(bundle).Patient; return ( ); }} ); } ``` -------------------------------- ### Format FHIR Dates and Times with Locale Support Source: https://context7.com/beda-software/fhir-emr/llms.txt Provides consistent formatting for FHIR date/time values with configurable locale-specific patterns. Utilizes functions from '@beda.software/emr/utils'. Allows setting custom formats for dates, times, and periods. ```typescript import { formatHumanDate, formatHumanDateTime, formatHumanTime, formatPeriodDateTime, setDateTimeFormats, humanDate, humanDateTime, } from '@beda.software/emr/utils'; // Configure custom date formats (call once at app initialization) setDateTimeFormats({ humanDate: 'MM/DD/YYYY', // US format humanDateYearMonth: 'MMMM YYYY', humanTime: 'h:mm A', // 12-hour format humanDateTime: 'MM/DD/YYYY h:mm A', }); // Format FHIR date strings const birthDate = formatHumanDate('1990-05-15'); // "05/15/1990" const yearMonth = formatHumanDate('2024-03'); // "March 2024" const yearOnly = formatHumanDate('2024'); // "2024" // Format FHIR dateTime strings const appointmentTime = formatHumanDateTime('2024-03-15T14:30:00Z'); // "03/15/2024 2:30 PM" // Format time only const startTime = formatHumanTime('14:30:00'); // "2:30 PM" // Format FHIR Period const encounterPeriod = formatPeriodDateTime({ start: '2024-03-15T09:00:00Z', end: '2024-03-15T09:30:00Z', }); // "03/15/2024 09:00-09:30" ``` -------------------------------- ### Perform AI-Powered FHIR Search with Natural Language Source: https://context7.com/beda-software/fhir-emr/llms.txt Interprets natural language queries to generate FHIR search parameters and table column configurations. Requires '@beda.software/emr/services' and '@beda.software/remote-data'. Outputs FHIR resource type, search parameters, and table column definitions. ```typescript import { performMagicSearch, MagicSearchResponse } from '@beda.software/emr/services'; import { isSuccess } from '@beda.software/remote-data'; // Perform AI-powered search async function searchWithNaturalLanguage(query: string) { const result = await performMagicSearch( 'Show me all diabetic patients over 50 with recent HbA1c results', 'tx-tools' // or 'semmatch' for semantic matching ); if (isSuccess(result)) { const { resourceType, searchParams, tableColumns } = result.data; // resourceType: 'Patient' // searchParams: { condition: 'diabetes', birthdate: 'le1974-01-01', ... } // tableColumns: [{ title: 'Name', dataIndex: 'name', fhirPath: 'Patient.name' }, ...] // Use the generated params to fetch resources const patients = await getFHIRResources(resourceType, searchParams); // Render table with generated columns return { patients, columns: tableColumns }; } } ``` -------------------------------- ### Generate Yup Validation Schemas from FHIR Questionnaires in TypeScript Source: https://context7.com/beda-software/fhir-emr/llms.txt Automatically generates Yup validation schemas from FHIR Questionnaire definitions using '@beda.software/emr/utils'. Supports standard item types, custom validators, and provides utilities for displaying answer values. Requires 'sdc-qrf' for Questionnaire types. ```typescript import { questionnaireToValidationSchema, questionnaireItemsToValidationSchema, getDisplay, getArrayDisplay, getAnswerDisplay, getAnswerCode, CustomYupTestsMap, } from '@beda.software/emr/utils'; import { FCEQuestionnaire, AnswerValue } from 'sdc-qrf'; // Generate validation schema from questionnaire const questionnaire: FCEQuestionnaire = { resourceType: 'Questionnaire', item: [ { linkId: 'name', type: 'string', required: true, maxLength: 100 }, { linkId: 'email', type: 'string', required: true, itemControl: { coding: [{ code: 'email' }] } }, { linkId: 'age', type: 'integer', required: true }, { linkId: 'weight', type: 'decimal' }, { linkId: 'birthDate', type: 'date', required: true }, ], }; // Custom validation tests for specific item controls const customTests: CustomYupTestsMap = { 'phone-input': [{ name: 'valid-phone', test: (value: string) => !value || /^\+?[1-9]\d{9,14}$/.test(value), message: 'Please enter a valid phone number', }], 'ssn-input': [{ name: 'valid-ssn', test: (value: string) => !value || /^\d{3}-\d{2}-\d{4}$/.test(value), message: 'SSN must be in format XXX-XX-XXXX', }], }; const schema = questionnaireToValidationSchema(questionnaire, customTests); // Validate form data try { await schema.validate(formValues, { abortEarly: false }); } catch (error) { console.log('Validation errors:', error.errors); } // Display answer values const codingValue: AnswerValue = { Coding: { code: 'male', display: 'Male' } }; console.log(getDisplay(codingValue)); // "Male" const dateValue: AnswerValue = { date: '1990-05-15' }; console.log(getDisplay(dateValue)); // "15 May 1990" // Get display for array of answers const medications = [ { value: { Coding: { code: 'med1', display: 'Aspirin' } } }, { value: { Coding: { code: 'med2', display: 'Ibuprofen' } } }, ]; console.log(getArrayDisplay(medications)); // "Aspirin, Ibuprofen" ``` -------------------------------- ### Authentication Service Source: https://context7.com/beda-software/fhir-emr/llms.txt Handles user login, logout, token management, and OAuth authorization flows, supporting password-based and federated authentication. ```APIDOC ## Authentication Service ### Description Handles user login, logout, token management, and OAuth authorization flows, supporting password-based and federated authentication. ### Methods - **POST /auth/login**: Authenticate user with email and password. - **POST /auth/logout**: Log out the current user. - **GET /auth/userinfo**: Retrieve information about the currently logged-in user. - **GET /auth/token**: Get the current authentication token. - **POST /auth/authorize**: Generate an OAuth authorization URL. - **POST /auth/token/exchange**: Exchange an authorization code for tokens. - **POST /auth/signin/identity**: Sign in using an identity token. ### Parameters #### Path Parameters - None for the core authentication service methods. #### Query Parameters - **authPath** (string) - Optional - Base path for authorization endpoints. - **params** (URLSearchParams) - Required for `getAuthorizeUrl` - Parameters for the authorization request. - **state** (object) - Optional for `getAuthorizeUrl` - State object to be passed in the authorization request. #### Request Body - **login**: `{ email: string, password: string }` - **exchangeAuthorizationCodeForToken**: `{ authorizationCode: string }` - **signinWithIdentityToken**: `{ idToken: string }` ### Request Example (Password Login) ```typescript import { login, setToken } from '@beda.software/emr/services'; const loginResult = await login({ email: 'doctor@hospital.com', password: 'secure-password-123', }); if (isSuccess(loginResult)) { setToken(loginResult.data.access_token); } ``` ### Request Example (Get User Info) ```typescript import { getUserInfo } from '@beda.software/emr/services'; const userInfoResult = await getUserInfo(); ``` ### Request Example (Generate OAuth URL) ```typescript import { getAuthorizeUrl } from '@beda.software/emr/services'; const authUrl = getAuthorizeUrl({ authPath: 'auth/authorize', params: new URLSearchParams({ client_id: 'emr-client', redirect_uri: 'https://emr.example.com/callback', response_type: 'code', scope: 'openid profile', }), state: { nextUrl: '/dashboard' }, }); ``` ### Request Example (Exchange Code for Token) ```typescript import { exchangeAuthorizationCodeForToken, setToken } from '@beda.software/emr/services'; const tokenResult = await exchangeAuthorizationCodeForToken(authorizationCode); if (isSuccess(tokenResult)) { setToken(tokenResult.data.access_token); } ``` ### Request Example (Logout) ```typescript import { doLogout } from '@beda.software/emr/services'; await doLogout(); // Redirects to '/' ``` ### Response #### Success Response (200) - **login**: `{ access_token: string, userinfo: object }` - **getUserInfo**: `object` (User details) - **getToken**: `string` (Current access token) - **exchangeAuthorizationCodeForToken**: `{ access_token: string, refresh_token: string, id_token: string }` #### Response Example (Login Success) ```json { "access_token": "eyJ...", "expires_in": 3600, "refresh_token": "def...", "token_type": "Bearer", "userinfo": { "sub": "user-123", "name": "Dr. John Doe", "email": "doctor@hospital.com" } } ``` ``` -------------------------------- ### Manage FHIR Questionnaire Forms with useQuestionnaireResponseFormData Hook (TypeScript) Source: https://context7.com/beda-software/fhir-emr/llms.txt The `useQuestionnaireResponseFormData` hook manages the lifecycle of FHIR Questionnaire forms, including loading, population, validation, saving, and data extraction. It can be used with a patient ID or a custom questionnaire service. Dependencies include `@beda.software/emr/hooks` and `@beda.software/remote-data`. ```typescript import { useQuestionnaireResponseFormData, usePatientQuestionnaireResponseFormData, questionnaireIdLoader, questionnaireServiceLoader, persistSaveService, persistWithProvenanceSaveService, } from '@beda.software/emr/hooks'; import { isSuccess, isFailure } from '@beda.software/remote-data'; // Basic usage with questionnaire ID function PatientIntakeForm({ patient }: { patient: Patient }) { const { response, handleSave } = usePatientQuestionnaireResponseFormData({ patient, questionnaireLoader: questionnaireIdLoader('patient-intake-form'), questionnaireResponseSaveService: persistWithProvenanceSaveService, launchContextParameters: [ { name: 'Organization', resource: currentOrganization }, ], }); const onSubmit = async (formData: QuestionnaireResponseFormData) => { const result = await handleSave(formData); if (isSuccess(result)) { console.log('Saved QR:', result.data.questionnaireResponse); console.log('Extracted resources:', result.data.extractedBundle); } else { console.error('Save failed:', result.error); } }; return ( {(formData) => ( )} ); } // Using custom questionnaire service const { response } = useQuestionnaireResponseFormData({ questionnaireLoader: questionnaireServiceLoader(async () => { return await service({ method: 'GET', url: '/Questionnaire/custom-form/$assemble', }); }), initialQuestionnaireResponse: { resourceType: 'QuestionnaireResponse', status: 'in-progress', }, }); ``` -------------------------------- ### Parse and Resolve FHIR References in TypeScript Source: https://context7.com/beda-software/fhir-emr/llms.txt Provides functions to parse FHIR references, extract resource type and ID, and resolve references within a FHIR Bundle. It requires the '@beda.software/emr/utils' package and FHIR resource types. ```typescript import { getFHIRReferenceData, getFHIRReferenceResourceType, getFHIRReferenceResourceId, resolveReference, } from '@beda.software/emr/utils'; import { Bundle, Patient, Practitioner, Reference } from 'fhir/r4b'; // Parse a FHIR reference const reference: Reference = { reference: 'Patient/patient-123' }; const { resourceType, id } = getFHIRReferenceData(reference); // resourceType: 'Patient', id: 'patient-123' // Get just the resource type or ID const type = getFHIRReferenceResourceType(reference); // 'Patient' const patientId = getFHIRReferenceResourceId(reference); // 'patient-123' // Resolve a reference within a bundle function getAppointmentParticipants(bundle: Bundle) { const appointments = extractBundleResources(bundle).Appointment; return appointments.map((appointment) => { const participants = appointment.participant?.map((p) => { if (p.actor?.reference?.startsWith('Patient/')) { return resolveReference(bundle, p.actor); } if (p.actor?.reference?.startsWith('Practitioner/')) { return resolveReference(bundle, p.actor); } return undefined; }); return { appointment, participants }; }); } ``` -------------------------------- ### FHIR Service API Source: https://context7.com/beda-software/fhir-emr/llms.txt Provides typed CRUD operations for FHIR resources, wrapping the aidbox-react library for interaction with Aidbox FHIR Server. ```APIDOC ## FHIR Service API ### Description Provides typed CRUD operations for FHIR resources, wrapping the aidbox-react library for interaction with Aidbox FHIR Server. ### Methods - **GET /fhir/{resourceType}/{id}**: Retrieve a single FHIR resource by its reference. - **GET /fhir/{resourceType}**: Search for FHIR resources with specified parameters. - **POST /fhir/{resourceType}**: Create a new FHIR resource. - **PUT /fhir/{resourceType}/{id}**: Update an existing FHIR resource (full replacement). - **PATCH /fhir/{resourceType}/{id}**: Partially update an existing FHIR resource. - **DELETE /fhir/{resourceType}/{id}**: Delete a FHIR resource. - **POST /fhir/{resourceType}/$operation**: Perform custom FHIR operations. ### Parameters #### Path Parameters - **resourceType** (string) - Required - The type of FHIR resource (e.g., 'Patient', 'Appointment'). - **id** (string) - Required - The ID of the FHIR resource. #### Query Parameters - **Parameters vary based on the FHIR resource and search criteria.** #### Request Body - **For POST/PUT/PATCH**: FHIR resource object conforming to the FHIR specification. - **For custom operations**: Operation-specific request payload. ### Request Example (Get Patient) ```typescript import { getFHIRResource } from '@beda.software/emr/services'; import { Patient } from 'fhir/r4b'; const patientResult = await getFHIRResource({ reference: 'Patient/patient-123' }); ``` ### Request Example (Search Appointments) ```typescript import { getFHIRResources } from '@beda.software/emr/services'; import { Appointment } from 'fhir/r4b'; const appointmentsResult = await getFHIRResources('Appointment', { patient: 'Patient/patient-123', status: 'booked', _sort: '-date', _count: 10, }); ``` ### Request Example (Create Patient) ```typescript import { createFHIRResource } from '@beda.software/emr/services'; import { Patient } from 'fhir/r4b'; const newPatient: Patient = { resourceType: 'Patient', name: [{ given: ['John'], family: 'Doe' }], birthDate: '1990-01-15', gender: 'male', }; const createResult = await createFHIRResource(newPatient); ``` ### Request Example (Patch Patient) ```typescript import { patchFHIRResource } from '@beda.software/emr/services'; import { Patient } from 'fhir/r4b'; const patchResult = await patchFHIRResource({ id: 'patient-123', resourceType: 'Patient', active: false, }); ``` ### Request Example (Custom Service Call) ```typescript import { service } from '@beda.software/emr/services'; import { Bundle } from 'fhir/r4b'; const customResult = await service({ method: 'POST', url: '/Questionnaire/$populate', data: parametersResource, }); ``` ### Response #### Success Response (200) - **data** (object) - The requested FHIR resource or a bundle of resources. - **error** (object) - An error object if the request failed. #### Response Example (Single Resource) ```json { "resourceType": "Patient", "id": "patient-123", "name": [ { "given": [ "John" ], "family": "Doe" } ], "birthDate": "1990-01-15", "gender": "male" } ``` #### Response Example (Bundle) ```json { "resourceType": "Bundle", "type": "searchset", "total": 2, "entry": [ { "fullUrl": "urn:uuid:1", "resource": { "resourceType": "Appointment", "id": "appt-1" } }, { "fullUrl": "urn:uuid:2", "resource": { "resourceType": "Appointment", "id": "appt-2" } } ] } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.