All files / services clinicDataService.ts

100% Statements 46/46
100% Branches 18/18
100% Functions 14/14
100% Lines 44/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208            3x                                                                 27x 27x                                 2x     2x 2x   2x 4x 4x                           3x 2x   1x     1x                               4x 1x       3x 2x 1x 1x     1x         1x     1x   1x 2x 1x     1x           2x         2x                           3x 3x 1x     2x                 2x 2x               1x 1x 5x 5x 3x               4x 4x   4x                 1x 1x              
import ClinicEntity from "@/myorm/clinic-entity";
import iClinicData from "@/interfaces/iClinicData";
import { EmptyStorageError, InvalidArgumentError } from "@/utils/ErrorTypes";
import AsyncStorage from '@react-native-async-storage/async-storage';
import logger from "@/utils/logger";
 
export const CLINIC_TIMESTAMP_KEY='clinic-data-timestamp';
 
/**
 * Stores data about a clinic.
 */
export interface Clinic {
    latitude?: number;
    longitude?: number;
    serviceArea?: string;
    name?: string;
    address?: string;
    contactInfo?: string;
    hours?: string;
    services?: Array<string>;
 
}
 
 
 
 
/**
 * Stores a set of clinics
 */
export class ClinicArray {
    clinics: Array<Clinic>;
    timeStamp: Date;
 
    /**
     * Stores a set of clinics 
     * @param clinics Array of clinic data.
     * @param timeStamp Time clinic data was originally created
     */
    constructor(clinics: Array<Clinic>, timeStamp: Date) {
        this.clinics = clinics;
        this.timeStamp = timeStamp;
    }
}
 
 
 
 
 
/** Stores clinic data using SQLite */
export default class ClinicData implements iClinicData {
 
    /**
     * Replace all clinics stored on device with new ones.
     * @param clinics A list of clinics. All attributes must be defined.
     * @effects stores each clinic as a row in the dabase
     */
    async storeClinics(clinics: ClinicArray): Promise<void> {
        logger.debug("storeClinics called")
 
 
        ClinicEntity.clear();
        await AsyncStorage.setItem(CLINIC_TIMESTAMP_KEY, clinics.timeStamp.toISOString());
 
        for (const clinic of clinics.clinics) {
            const clinicEntity = new ClinicEntity(clinic);
            await clinicEntity.save();
        }
 
        
 
    }
 
    /**
     * Gets a list of all clinics stored on device.
     * @return An object with all the clinic's data, with a timestamp of the last time it was updated
     *      or null if no data is stored.
     * @throws EmptyStorageError If no clinics are stored.
     */
    async getClinics(): Promise<ClinicArray> {
        if (await this.isStorageEmpty()) {
            throw new EmptyStorageError("No clinic data available locally");
        }
        const clinics = await ClinicEntity.find();
 
        
        return new ClinicArray(clinics, await this.getTimeStamp());
    }
 
    /**
     * Search for clinics that are stored on device.
     * @param input The value to search for.
     * @param column The text column to search in, if left blank all column are searched.
     *  The column must be a valid text column name in the ClinicData table.
     * @return An array of all of the clinics containing `input`.
     * @throws EmptyStorageError If no clinics are stored.
     * @throws InvalidArgumentError If `column` is not a valid column. 
     *      Use `Clinicdata.getTextColumns()` to get a list of valid columns.
     */
    async searchClinics(input:string, column?:string): Promise<ClinicArray> {
        let clinicArray: Array<Clinic>;
 
        if (await this.isStorageEmpty()) {
            throw new EmptyStorageError("No clinic data available locally");
        }
 
 
        if (column) {
            if (!(await this.isValidTextColumn(column))) {
                const validColumns = await this.getTextColumns();
                throw new InvalidArgumentError(`Invalid column name: ${column}, \n\tValid column names are: ${validColumns.join(', ')}`);
            }
            
            clinicArray = await ClinicEntity.queryObjs(`SELECT * from $table WHERE ${column} LIKE ?`, `%${input}%`);
 
        }
        else {
 
            let query = `SELECT * from $table WHERE`;
 
 
            const textColumns = await this.getTextColumns();
            
            textColumns.forEach((column, index) => {
                if (index === 0) {
                    query += ` ${column} LIKE ?`;
                }
                else {
                    query += ` OR ${column} LIKE ?`;
                }
            });
 
 
 
            clinicArray = await ClinicEntity.queryObjs(query, ...(textColumns.map(() => `%${input}%`)));
        }
 
        
        
        return new ClinicArray(
            clinicArray,
            await this.getTimeStamp()
        );
 
    }
 
 
    /**
     * Gets the time the clinic data was created
     * @return The time the data was created
     * @throws EmptyStorageError If no clinics are stored.
     */
    async getTimeStamp(): Promise<Date> {
        const timeStr = await AsyncStorage.getItem(CLINIC_TIMESTAMP_KEY);
        if (timeStr == null) {
            throw new EmptyStorageError("No clinic data available locally");
        }
 
        return new Date(timeStr);
 
    }
    /**
     * Checks if a string is a valid text column name.
     * @param columnName Name of the column to validate
     * @returns `true` if column is valid, `false` otherwise.
     */
    async isValidTextColumn(columnName: string): Promise<boolean> {
        const columns = await this.getTextColumns();
        return columns.some(col => col === columnName);
    }
 
    /**
     * Gets a list of text column names.
     * @returns A list of text column names.
     */
    async getTextColumns(): Promise<string[]> {
        const columns = await ClinicEntity.getColumns();
        return columns.filter(col => {
            const type = col.type;
            return type === "TEXT" || type?.includes("VARCHAR") || type?.includes("CHARACTER");
          }).map(col => col.name!);
    }
 
    /**
     * Checks if the clinic data storage is empty.
     * @returns `true` no clinics are stored, `false` otherwise.
     */
    async isStorageEmpty(): Promise<boolean> {
        const timeStr = await AsyncStorage.getItem(CLINIC_TIMESTAMP_KEY);
        const count = await ClinicEntity.count();
        
        return timeStr === null || timeStr === '' || count === 0;
    }
 
 
    /**
     * Deletes all stored clinic data and timestamp
     * @effects removes all rows in the clinic data table 
     */
    async emptyStorage(): Promise<void> {
        await ClinicEntity.clear();
        await AsyncStorage.removeItem(CLINIC_TIMESTAMP_KEY);
    }
 
 
}