All files / src/auth/session/storage custom.ts

100% Statements 36/36
100% Branches 18/18
100% Functions 5/5
100% Lines 32/32

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 7118x   18x   18x   9x 9x 9x   9x 9x 9x     18x   9x   1x           18x     10x   1x       9x 7x 4x 1x     4x 3x 2x 2x   2x 1x     2x   1x         2x       18x   4x   1x         18x  
import {Session} from '../session';
import {SessionStorage} from '../session_storage';
import * as ShopifyErrors from '../../../error';
 
export class CustomSessionStorage implements SessionStorage {
  constructor(
    readonly storeCallback: (session: Session) => Promise<boolean>,
    readonly loadCallback: (id: string) => Promise<Session | Record<string, unknown> | undefined>,
    readonly deleteCallback: (id: string) => Promise<boolean>,
  ) {
    this.storeCallback = storeCallback;
    this.loadCallback = loadCallback;
    this.deleteCallback = deleteCallback;
  }
 
  public async storeSession(session: Session): Promise<boolean> {
    try {
      return await this.storeCallback(session);
    } catch (error) {
      throw new ShopifyErrors.SessionStorageError(
        `CustomSessionStorage failed to store a session. Error Details: ${error}`,
      );
    }
  }
 
  public async loadSession(id: string): Promise<Session | undefined> {
    let result: Session | Record<string, unknown> | undefined;
    try {
      result = await this.loadCallback(id);
    } catch (error) {
      throw new ShopifyErrors.SessionStorageError(
        `CustomSessionStorage failed to load a session. Error Details: ${error}`,
      );
    }
    if (result) {
      if (result instanceof Session) {
        if (result.expires && typeof result.expires === 'string') {
          result.expires = new Date(result.expires);
        }
 
        return result;
      } else if (result instanceof Object && 'id' in result) {
        let session = new Session(result.id as string);
        session = {...session, ...result};
 
        if (session.expires && typeof session.expires === 'string') {
          session.expires = new Date(session.expires);
        }
 
        return session;
      } else {
        throw new ShopifyErrors.SessionStorageError(
          `Expected return to be instanceof Session, but received instanceof ${result!.constructor.name}.`,
        );
      }
    } else {
      return undefined;
    }
  }
 
  public async deleteSession(id: string): Promise<boolean> {
    try {
      return await this.deleteCallback(id);
    } catch (error) {
      throw new ShopifyErrors.SessionStorageError(
        `CustomSessionStorage failed to delete a session. Error Details: ${error}`,
      );
    }
  }
}