Herman Andres Figueroa
Herman Andres Figueroa

Reputation: 523

TypeScript: Best way to create Data access layer

Good afternoon, I am creating an application in ionic using angular where currently it handles two connection modes: connected if the user has internet access and disconnected if they do not have it

Currently I have a feature and it is that if the user is in connected mode he must call an API otherwise he must make calls to queries in SQLite:

component.example.ts

getUsers () {
  this.dataLayer.getUsers().subscribe (...)
}

data-access-layer.ts

getUsers () {
  if (this.connectionMode == 'online') {
     this.httpcliente.post (...)
  } else {
     this.sqliteclient.query ("...")
  }
}

My question would be what is the best way to implement this strategy, since the way to make conditions to validate if the connection is one or the other does not seem the best to me or maybe use an enumeration

enum AccessDataSqLite {
   getUsers = "...",
   getData = "...",
}

I would appreciate if you can send me references, link or a better way to implement this strategy

Thank you very much

Upvotes: 4

Views: 2104

Answers (1)

enno.void
enno.void

Reputation: 6579

If you want to build this behavior, you can simply implement the Strategy pattern

Example:

import { Injectable } from "@angular/core";
import { fromEvent, merge } from "rxjs";
import { startWith, map } from "rxjs/operators";

interface Strategy {
  getData1(): any;
  anotherMethod(): any;
}

class SQLStrategy implements Strategy {
  getData1() {
    console.log("SQl", "getData1");
  }

  anotherMethod() {
    console.log("SQl", "anotherMethod");
  }
}

class HTTPStrategy implements Strategy {
  getData1() {
    console.log("HTTP", "getData1");
  }

  anotherMethod() {
    console.log("HTTP", "anotherMethod");
  }
}

@Injectable()
export class DataLayerService {
  private strategy;

  constructor() {
    // init strats
    const sqlStrategy = new SQLStrategy();
    const httpStrategy = new HTTPStrategy();

    merge(fromEvent(window, "online"), fromEvent(window, "offline"))
      .pipe(
        startWith(1),
        map(x => navigator.onLine)
      )
      .subscribe(x => {
        console.log("navigator.onLine", x);
        this.strategy = x ? httpStrategy : sqlStrategy;
      });
  }

  public getData1() {
    this.strategy.getData1();
  }

  public anotherMethod() {
    this.strategy.anotherMethod();
  }
}

Stackblitz: https://stackblitz.com/edit/angular-ivy-fggs4r?file=src/app/data-layer.service.ts

Upvotes: 6

Related Questions