Observable function ignoring code "return defer"

Viewed 31

recently I am working with Angular 11, I am trying to do a function that checks if the account is allowed to do an action however I have to get it whenever there is a change in the SAS Token, that said, I did the functions below

      /**
   *Verify if SAS has permissions
   * @param sasUri Sas address
   * @param permissions The permissions to verify
   * @returns Boolean Value
   */
  async hasPermissions(sasUri: string, permissions: SASInformationPermission[]): Promise<boolean> {
    const permissionAccount = await this.getSASUriInformation(sasUri).toPromise();
    return permissions.every((permission) => {
      permissionAccount.signedPermissions.includes(permission);
    });
  }

  /**
   * Get validation of action permission
   * @param sasUri Sas address
   * @param action The action to check
   * @returns Boolean value
   */
  hasActionPermission(sasUri: string, action: Action): Observable<boolean> {
    return defer(async () => {
      let permission: SASInformationPermission[];
      if (action === 'upload') {
        permission = [
          SASInformationPermission.Read,
          SASInformationPermission.List,
          SASInformationPermission.Write,
        ];
      } else {
        permission = [SASInformationPermission.List, SASInformationPermission.Read];
      }

      return await this.hasPermissions(sasUri, permission);
    });
  }

the "hasPermissions" function takes and checks if the SAS has access to the action that is passed by parameter and the "HasActionPermission" function calls the above function to have a Boolean value

the function "HasActionPermission" simply does not enter the "return defer" what can it be?

1 Answers

Embrace observables. You seem to be going back and forth between observables and promises, but this seems entirely unnecessary. Feel free to call toPromise() after hasActionPermissions() is called.

Here's an rxjs-only rewrite:

hasPermissions(sasUri: string, permissions: SASInformationPermission[]): Observable<boolean> {
  return this.getSASUriInformation(sasUri).pipe(
    map(acct => permissions.every(x => acct.signedPermissions.includes(x)))
  );
}

hasActionPermission(sasUri: string, action: Action): Observable<boolean> {
  const permission: SASInformationPermission[] = (action === 'upload') 
    ? [SASInformationPermission.Read, SASInformationPermission.List, SASInformationPermission.Write]
    : [SASInformationPermission.List, SASInformationPermission.Read];
    
  return this.hasPermissions(sasUri, permission);
}

It's a lot cleaner, and it will be cold until you call subscribe() or toPromise(), no need for defer().

Related