All files / src/database/in-memory database.ts

83.9% Statements 73/87
72.41% Branches 21/29
90.9% Functions 40/44
90% Lines 72/80

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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 4202548x                             1x           1x                                                     79x 79x 79x 79x 79x 79x                   136x 136x     136x                   404x                                         231x   231x 231x   231x   231x 231x 231x                 8x                                       4x 4x       4x     4x 4x       4x       4x   4x                             19x 19x 12x   19x     79x                         168x     95x                                       152x     1x       1x 1x       66x 66x                   4x                           79x               72x     6x 5x       40x 40x             1x     1x                         4x     4x 2x       16x 16x                   1x     1x                             4x     4x 2x       7x 7x               1x     1x                           4x     4x 2x                         7x 7x                         1x                         1x                            
import DatabaseInterface from "@cooper/backend/src/database/in-memory/database";
import { z } from "zod";
import {
  Auth$Session,
  Auth$SessionSchema,
  Auth$User,
  Auth$UserSchema,
  Budgeting$Account,
  Budgeting$AccountSchema,
  Budgeting$Category,
  Budgeting$CategorySchema,
  Budgeting$Transaction,
  Budgeting$TransactionSchema,
  Budgeting$Workspace,
  Budgeting$WorkspaceSchema,
} from "@cooper/ts-rest/src/types";
 
/*
 * An simple implementation of an in-memory database. Only for use in testing or demonstration,
 * as it is not optimised for performance or security.
 */
export default class InMemoryDatabase implements DatabaseInterface {
  // Authentication data structures
  private authUsers: Map<string, Auth$User>;
  private authSessions: Map<number, Auth$Session>;
 
  // Budgeting data structures
  private budgetingWorkspaces: Map<number, Budgeting$Workspace>;
  private budgetingAccounts: Map<number, Budgeting$Account>;
  private budgetingCategories: Map<number, Budgeting$Category>;
  private budgetingTransactions: Map<number, Budgeting$Transaction>;
 
  // Initialise default data-store values
  constructor({
    initialUsers,
    initialSessions,
    initialWorkspaces,
    initialAccounts,
    initialCategories,
    initialTransactions,
  }: {
    initialUsers?: Map<string, Auth$User>;
    initialSessions?: Map<number, Auth$Session>;
    initialWorkspaces?: Map<number, Budgeting$Workspace>;
    initialAccounts?: Map<number, Budgeting$Account>;
    initialCategories?: Map<number, Budgeting$Category>;
    initialTransactions?: Map<number, Budgeting$Transaction>;
  }) {
    this.authUsers = initialUsers ?? new Map();
    this.authSessions = initialSessions ?? new Map();
    this.budgetingWorkspaces = initialWorkspaces ?? new Map();
    this.budgetingAccounts = initialAccounts ?? new Map();
    this.budgetingCategories = initialCategories ?? new Map();
    this.budgetingTransactions = initialTransactions ?? new Map();
  }
 
  /**
   * Generates an unused numeric key for a map which uses integers as keys.
   * Increments the key by current size of map, guarantees non-collision.
   * @param map Map of which to generate the key for
   * @returns {number} Numeric key
   */
  _keyGen<ValueType>(map: Map<number, ValueType>): number {
    let newKey = map.size + 1;
    while (map.has(newKey)) {
      newKey++;
    }
    return newKey;
  }
 
  /**
   * Get a record from a generic map. Returns undefined if record not set.
   * @param map Map to fetch record
   * @param key Key of record to be fetched
   * @returns
   */
  _genericGet<KeyType, ValueType>(map: Map<KeyType, ValueType>, key: KeyType) {
    return map.get(key);
  }
 
  /**
   * Generic creation function for a record for a map used by this in-memory
   * database. Parses the given data based on the given schema
   *
   * @param map Map of which record will be added to
   * @param schema Zod schema that will be used to parse
   * @param key Key of key-value pair that will be assigned to this new record in the map
   * @param data Data to add, will be parsed using Zod based on given schema
   * @param overwrite Set to true if existing record should be overwritten if present. Defaults to false
   * @returns Returns the newly created record, or an Error if failed to create
   */
  _genericCreate<KeyType, DataType extends z.ZodTypeAny>(
    map: Map<KeyType, z.infer<DataType>>,
    schema: DataType,
    key: KeyType,
    data: unknown,
    overwrite: boolean = false,
  ): z.infer<DataType> {
    Iif (!overwrite && map.get(key) != null) return new Error("Record with key already exists");
 
    const result = schema.safeParse(data) as z.infer<DataType>;
    Iif (!result.success) return result.error;
 
    map.set(key, result.data);
 
    const newRecord = map.get(key);
    Iif (!newRecord) return new Error("Failed to create record");
    return newRecord;
  }
 
  /**
   * Deletes a record from a generic map.
   * @param map Map from which record should be deleted
   * @param key Key of record to be deleted
   */
  _genericDelete<KeyType, ValueType>(map: Map<KeyType, ValueType>, key: KeyType) {
    map.delete(key);
  }
 
  /**
   * Updates a record in a generic map. All fields in data are optional,
   * and only fields that are set will be updated.
   * @param map Map to be updated
   * @param schema Zod schema of map value, used to validate data
   * @param key Key of record to be updated
   * @param data Data which will update record, must be an object
   * @returns
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  _genericUpdate<KeyType, DataType extends z.ZodObject<any, any, any, any>>(
    map: Map<KeyType, z.infer<DataType>>,
    schema: DataType,
    key: KeyType,
    data: unknown,
  ) {
    // Check an existing record exists
    const existingRecord = map.get(key);
    Iif (!existingRecord) return new Error("Record with key does not exist");
 
    // Derive a new object schema where all key/values are optional (the caller can
    // change only the fields they want to)
    const partialSchema = schema.partial();
 
    // Parse the data using this partial schema
    const result = partialSchema.safeParse(data);
    Iif (!result.success) return result.error;
 
    // Join existing data with updated data, overwriting
    // existing data if the field has been set
    const newData = {
      ...existingRecord,
      ...result.data,
    };
    map.set(key, newData);
 
    return newData;
  }
 
  /**
   * Filter out all elements in a generic map based on given predicate. Each key/value
   * pair will be passed to the predicate function. If the predicate returns true, the element
   * will be included in the returned array.
   * @param map Map of which records are filtered
   * @param predicate Predicate function, must return a boolean
   * @returns
   */
  _genericMapFilter<KeyType, DataType>(
    map: Map<KeyType, DataType>,
    predicate: (value: DataType, key: KeyType, map: Map<KeyType, DataType>) => boolean,
  ): DataType[] {
    const filterItems: DataType[] = [];
    map.forEach((value, key, map) => {
      if (predicate(value, key, map)) filterItems.push(value);
    });
    return filterItems;
  }
 
  auth = {
    /*
     * ======================
     *      Auth.Users
     * ======================
     */
    users: {
      isValidLogin: (username: string, password: string) => {
        const user = this.authUsers.get(username.toLowerCase());
        Iif (user == null) return false;
        return user.password === password;
      },
      getUser: (username: string) => {
        return this._genericGet(this.authUsers, username.toLowerCase());
      },
      createUser: (user: Auth$User) => {
        return this._genericCreate(this.authUsers, Auth$UserSchema, user.username.toLowerCase(), user);
      },
      updateUser: (username: string, firstName?: string, lastName?: string, password?: string) => {
        return this._genericUpdate(this.authUsers, Auth$UserSchema, username.toLowerCase(), {
          firstName,
          lastName,
          password,
        });
      },
      deleteUser: (username: string) => {
        this._genericDelete(this.authUsers, username.toLowerCase());
      },
    },
    /*
     * ======================
     *     Auth.Sessions
     * ======================
     */
    sessions: {
      getSession: (sessionId: number) => {
        return this._genericGet(this.authSessions, sessionId);
      },
      getUserSessions: (username: string) => {
        Iif (this.auth.users.getUser(username) == null)
          // return new Error("User does not exist");
          return [];
 
        return this._genericMapFilter(this.authSessions, (value) => {
          return value.username.toLowerCase() === username.toLowerCase();
        });
      },
      createSession: (username: string, ip: string, userAgent: string, started: Date, expires: Date) => {
        const newKey = this._keyGen(this.authSessions);
        return this._genericCreate(this.authSessions, Auth$SessionSchema, newKey, {
          sessionId: newKey,
          username,
          ip,
          userAgent,
          started,
          expires,
        });
      },
      deleteSession: (sessionId: number) => {
        this._genericDelete(this.authSessions, sessionId);
      },
      updateSession: (sessionId: number, ip?: string, userAgent?: string, started?: Date, expires?: Date) => {
        return this._genericUpdate(this.authSessions, Auth$SessionSchema, sessionId, {
          sessionId,
          ip,
          userAgent,
          started,
          expires,
        });
      },
    },
  };
 
  budgeting = {
    /*
     * ======================
     *  Budgeting.Workspaces
     * ======================
     */
    workspaces: {
      getWorkspace: (workspaceId: number) => {
        return this._genericGet(this.budgetingWorkspaces, workspaceId);
      },
      getUserWorkspaces: (username: string) => {
        return this._genericMapFilter(this.budgetingWorkspaces, (value) => {
          return value.users.includes(username);
        });
      },
      createWorkspace: (username: string, workspaceName: string) => {
        const newKey = this._keyGen(this.budgetingWorkspaces);
        return this._genericCreate(this.budgetingWorkspaces, Budgeting$WorkspaceSchema, newKey, {
          workspaceId: newKey,
          name: workspaceName,
          users: [username],
        });
      },
      deleteWorkspace: (workspaceId: number) => {
        this._genericDelete(this.budgetingWorkspaces, workspaceId);
      },
      updateWorkspace: (workspaceId: number, name: string, users: string[]) => {
        return this._genericUpdate(this.budgetingWorkspaces, Budgeting$WorkspaceSchema, workspaceId, {
          name,
          users,
        });
      },
    },
    /*
     * ======================
     *   Budgeting.Accounts
     * ======================
     */
    accounts: {
      getAccount: (accountId: number) => {
        return this._genericGet(this.budgetingAccounts, accountId);
      },
      getWorkspaceAccounts: (workspace: number) => {
        return this._genericMapFilter(this.budgetingAccounts, (value) => {
          return value.workspace === workspace;
        });
      },
      createAccount: (name: string, bank: string, description: string, workspace: number, createdBy: string) => {
        const newKey = this._keyGen(this.budgetingAccounts);
        return this._genericCreate(this.budgetingAccounts, Budgeting$AccountSchema, newKey, {
          accountId: newKey,
          name,
          bank,
          description,
          workspace,
          createdBy,
        });
      },
      deleteAccount: (accountId: number) => {
        this._genericDelete(this.budgetingAccounts, accountId);
      },
      updateAccount: (accountId: number, name?: string, bank?: string, description?: string, createdBy?: string) => {
        return this._genericUpdate(this.budgetingAccounts, Budgeting$AccountSchema, accountId, {
          name,
          bank,
          description,
          createdBy,
        });
      },
    },
    /*
     * ======================
     *  Budgeting.Categories
     * ======================
     */
    categories: {
      getCategory: (categoryId: number) => {
        return this._genericGet(this.budgetingCategories, categoryId);
      },
      getWorkspaceCategories: (workspace: number) => {
        return this._genericMapFilter(this.budgetingCategories, (category) => {
          return category.workspace === workspace;
        });
      },
      createCategory: (name: string, createdBy: string, workspace: number) => {
        const newKey = this._keyGen(this.budgetingCategories);
        return this._genericCreate(this.budgetingCategories, Budgeting$CategorySchema, newKey, {
          categoryId: newKey,
          name,
          createdBy,
          workspace,
        });
      },
      deleteCategory: (categoryId: number) => {
        this._genericDelete(this.budgetingCategories, categoryId);
      },
      updateCategory: (categoryId: number, workspace: number, name?: string, createdBy?: string) => {
        return this._genericUpdate(this.budgetingCategories, Budgeting$CategorySchema, categoryId, {
          name,
          createdBy,
          workspace,
        });
      },
    },
    /*
     * ======================
     * Budgeting.Transactions
     * ======================
     */
    transactions: {
      getTransaction: (transactionId: number) => {
        return this._genericGet(this.budgetingTransactions, transactionId);
      },
      getWorkspaceTransactions: (workspace: number) => {
        return this._genericMapFilter(this.budgetingTransactions, (transaction) => {
          return transaction.workspace === workspace;
        });
      },
      createTransaction: (
        date: Date,
        description: string,
        createdBy: string,
        account: number,
        category: string,
        amount: number,
        comments: string | null,
        workspace: number,
      ) => {
        const newKey = this._keyGen(this.budgetingTransactions);
        return this._genericCreate(this.budgetingTransactions, Budgeting$TransactionSchema, newKey, {
          transactionId: newKey,
          date,
          description,
          createdBy,
          account,
          category,
          amount,
          comments,
          workspace,
        });
      },
      deleteTransaction: (transactionId: number) => {
        return this._genericDelete(this.budgetingTransactions, transactionId);
      },
      updateTransaction: (
        transactionId: number,
        workspace: number,
        date?: Date,
        description?: string,
        createdBy?: string,
        account?: number,
        category?: string,
        amount?: number,
        comments?: string | null,
      ) => {
        return this._genericUpdate(this.budgetingTransactions, Budgeting$TransactionSchema, transactionId, {
          date,
          description,
          createdBy,
          account,
          category,
          amount,
          comments,
          workspace,
        });
      },
    },
  };
}