-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
rbento1096
committed
Feb 20, 2024
1 parent
577994c
commit b55b8d1
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import { Injectable } from '@angular/core'; | ||
import { IDEAApiService } from '@idea-ionic/common'; | ||
|
||
import { Connection } from '@models/connection.model'; | ||
|
||
@Injectable({ providedIn: 'root' }) | ||
export class ConnectionsService { | ||
private connections: Connection[]; | ||
|
||
/** | ||
* The number of connections to consider for the pagination, when active. | ||
*/ | ||
MAX_PAGE_SIZE = 24; | ||
|
||
constructor(private api: IDEAApiService) {} | ||
|
||
private async loadList(): Promise<void> { | ||
this.connections = (await this.api.getResource(['connections'])).map(c => new Connection(c)); | ||
} | ||
|
||
/** | ||
* Get (and optionally filter) the list of connections. | ||
* Note: it can be paginated. | ||
* Note: it's a slice of the array. | ||
*/ | ||
async getList(options: { | ||
force?: boolean; | ||
withPagination?: boolean; | ||
pending?: boolean; | ||
startPaginationAfterId?: string; | ||
}): Promise<Connection[]> { | ||
if (!this.connections || options.force) await this.loadList(); | ||
if (!this.connections) return null; | ||
|
||
let filteredList = this.connections.slice(); | ||
|
||
filteredList = filteredList.filter(c => (options.pending ? c.isPending : !c.isPending)); | ||
|
||
if (options.withPagination && filteredList.length > this.MAX_PAGE_SIZE) { | ||
let indexOfLastOfPreviousPage = 0; | ||
if (options.startPaginationAfterId) | ||
indexOfLastOfPreviousPage = filteredList.findIndex(x => x.connectionId === options.startPaginationAfterId) || 0; | ||
filteredList = filteredList.slice(0, indexOfLastOfPreviousPage + this.MAX_PAGE_SIZE); | ||
} | ||
|
||
return filteredList; | ||
} | ||
|
||
/** | ||
* Insert a new connection. | ||
*/ | ||
async insert(userId: string): Promise<Connection> { | ||
return new Connection(await this.api.postResource(['connections'], { body: { userId } })); | ||
} | ||
/** | ||
* Delete a connection. | ||
*/ | ||
async delete(connection: Connection): Promise<void> { | ||
await this.api.deleteResource(['connections', connection.connectionId]); | ||
} | ||
} |