ngx-pwa
Version:
Provides functionality around the progressive web app functionality in angular. Most notably the an approach to cache POST, UPDATE and DELETE requests.
470 lines (452 loc) • 17.2 kB
TypeScript
import * as i0 from '@angular/core';
import { NgZone, InjectionToken, OnInit } from '@angular/core';
import { HttpContextToken, HttpRequest, HttpClient, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Observable } from 'rxjs';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { DomSanitizer } from '@angular/platform-browser';
import { SwPush, SwUpdate } from '@angular/service-worker';
/**
* The type for the synchronize dialog data.
*/
interface SynchronizeDialogData {
/**
* The title of the dialog.
*/
title?: string;
/**
* The label for the close button.
*/
closeButtonLabel?: string;
/**
* The label for the button that syncs everything.
*/
syncAllButtonLabel?: string;
/**
* The label for the button that undoes all local changes.
*/
undoAllButtonLabel?: string;
}
/**
* Model for providing information about a request.
* Is needed for various things when the request is cached locally.
*/
interface RequestMetadata {
/**
* The idKey of the request.
* @default 'id'
*/
idKey?: keyof BaseEntityType<unknown>;
/**
* The type of the request body.
* Is needed to apply offline request to local data.
*/
type: string;
/**
* How to display the request inside the sync dialog.
* Can use html.
*/
displayValue?: string;
}
declare const NGX_PWA_HTTP_CONTEXT_METADATA: HttpContextToken<RequestMetadata | undefined>;
/**
* The internal request metadata.
* Sets default values.
*/
declare class RequestMetadataInternal implements RequestMetadata {
idKey: keyof BaseEntityType<unknown>;
type: string;
displayValue: string;
constructor(request: HttpRequest<unknown>, data?: RequestMetadata);
}
/**
* The Generic Base EntityType.
*/
type BaseEntityType<T> = {
[K in keyof T]: unknown;
};
declare const NGX_PWA_OFFLINE_SERVICE: InjectionToken<void>;
/**
* The type of a cached offline request.
* Contains the http request as well as some metadata.
*/
interface CachedRequest<T> {
/**
* The actual http request.
*/
request: HttpRequest<T>;
/**
* The metadata for that request.
*/
metadata: RequestMetadataInternal;
}
/**
* The base class for an offline service.
*/
declare class NgxPwaOfflineService {
private readonly http;
private readonly snackBar;
private readonly zone;
private readonly platformId;
/**
* The key under which any requests are saved in local storage.
*/
readonly CACHED_REQUESTS_KEY: string;
/**
* The prefix of offline generated ids.
* Is used to check if a request still has unresolved dependencies.
*/
readonly OFFLINE_ID_PREFIX: string;
/**
* A snackbar message to display when the synchronization of all cached requests has been finished.
*/
protected readonly ALL_SYNC_FINISHED_SNACK_BAR_MESSAGE: string;
/**
* A snackbar message to display when the synchronization of all cached requests fails.
*/
protected readonly ALL_SYNC_FAILED_SNACK_BAR_MESSAGE: string;
/**
* A snackbar message to display when the synchronization of a single cached requests has been finished.
*/
protected readonly SINGLE_SYNC_FINISHED_SNACK_BAR_MESSAGE: string;
/**
* A snackbar message to display when the synchronization of a single cached requests fails.
*/
protected readonly SINGLE_SYNC_FAILED_SNACK_BAR_MESSAGE: string;
/**
* Whether or not the user has no internet connection.
*/
isOffline: boolean;
/**
* A subject of all the requests that have been done while offline.
* Needs to be used for applying offline data or syncing the requests to the api.
*/
private readonly cachedRequestsSubject;
/**
* The currently stored cached requests (if there are any).
*/
get cachedRequests(): CachedRequest<unknown>[];
set cachedRequests(cachedRequests: CachedRequest<unknown>[]);
constructor(http: HttpClient, snackBar: MatSnackBar, zone: NgZone, platformId: Object);
/**
* Applies any offline data that has been cached to the given values.
* @param type - The type of the provided entities. Is needed to check if any cached requests of the same type exist.
* @param entities - The already existing data.
* @returns The already existing entities extended/modified by the offline cached requests.
*/
applyOfflineData<EntityType extends BaseEntityType<EntityType>>(type: string, entities: EntityType[]): EntityType[];
/**
* Applies an UPDATE to an entity without sending a request to the server.
* @param changes - The changes that should be made to the entity.
* @param entity - The entity that should be updated.
* @returns The updated entity.
*/
protected updateOffline<EntityType extends BaseEntityType<EntityType>>(changes: Partial<EntityType>, entity: EntityType): EntityType;
/**
* Sends a specific cached request to the server.
* @param request - The request that should be synced.
*/
sync<T>(request: CachedRequest<T>): Promise<void>;
/**
* Sends all cached requests to the server. Tries to handle dependencies of requests on each other.
*/
syncAll(): Promise<void>;
/**
* The recursive method used to syn all requests to the api.
*/
protected syncAllRecursive(): Promise<void>;
/**
* Sends a single cached request to the server.
* @param request - The request that should be synced.
* @returns A promise of the request result.
*/
protected syncSingleRequest<T>(request: CachedRequest<T>): Promise<T>;
private updateOfflineIdsInRequests;
/**
* Calls http.post/patch/delete etc. On the provided request.
* @param request - The request that should be sent.
* @returns The observable of the request or undefined if something went wrong.
*/
protected request<EntityType extends BaseEntityType<EntityType>>(request: CachedRequest<EntityType>): Observable<EntityType> | undefined;
/**
* Checks if the given request has an unresolved dependency by looking for the keyword 'offline' inside of it.
* @param request - The request that should be checked.
* @returns Whether or no the given request has an unresolved dependency.
*/
hasUnresolvedDependency(request: CachedRequest<unknown>): boolean;
/**
* Removes a single request from the cache.
* @param request - The request that should be removed.
*/
removeSingleRequest(request: CachedRequest<unknown>): void;
}
/**
* Shows a offline warning when the user is not online.
*/
declare class NgxPwaOfflineStatusBarComponent<OfflineServiceType extends NgxPwaOfflineService> implements OnInit {
readonly offlineService: OfflineServiceType;
/**
* The message to display when the user is offline.
* @default 'Offline'
*/
offlineMessage: string;
/**
* The message to display when the user has changes that aren't synced to the api.
* @default 'Unsaved Changes'
*/
unsavedChangesMessage: string;
/**
* Whether or not to display a badge that shows the amount of cached requests and can open a dialog to sync changes to the server.
*/
displayUnsavedChangesSynchronizeBadge: boolean;
/**
* Configuration data for the Synchronize Dialog.
*/
synchronizeDialogData?: SynchronizeDialogData;
constructor(offlineService: OfflineServiceType);
ngOnInit(): void;
static ɵfac: i0.ɵɵFactoryDeclaration<NgxPwaOfflineStatusBarComponent<any>, never>;
static ɵcmp: i0.ɵɵComponentDeclaration<NgxPwaOfflineStatusBarComponent<any>, "ngx-pwa-offline-status-bar", never, { "offlineMessage": { "alias": "offlineMessage"; "required": false; }; "unsavedChangesMessage": { "alias": "unsavedChangesMessage"; "required": false; }; "displayUnsavedChangesSynchronizeBadge": { "alias": "displayUnsavedChangesSynchronizeBadge"; "required": false; }; "synchronizeDialogData": { "alias": "synchronizeDialogData"; "required": false; }; }, {}, never, never, true, never>;
}
/**
* Displays a badge with the amount of cached offline request.
* Can be clicked to open a dialog to sync cached requests to the server.
*/
declare class NgxPwaSynchronizeBadgeComponent<OfflineServiceType extends NgxPwaOfflineService> {
readonly offlineService: OfflineServiceType;
private readonly dialog;
/**
* Configuration data for the Synchronize Dialog.
*/
synchronizeDialogData?: SynchronizeDialogData;
constructor(offlineService: OfflineServiceType, dialog: MatDialog);
/**
* Opens the dialog for syncing cached requests to the server.
*/
openSyncDialog(): void;
static ɵfac: i0.ɵɵFactoryDeclaration<NgxPwaSynchronizeBadgeComponent<any>, never>;
static ɵcmp: i0.ɵɵComponentDeclaration<NgxPwaSynchronizeBadgeComponent<any>, "ngx-pwa-synchronize-badge", never, { "synchronizeDialogData": { "alias": "synchronizeDialogData"; "required": false; }; }, {}, never, never, true, never>;
}
/**
* Contains HelperMethods around handling the purification of html strings.
* Is less strict than angular's own sanitizer.
*/
declare abstract class PurifyUtilities {
/**
* Sanitizes the given source string.
* @param source - The html value as a string.
* @returns A sanitized string of the given source.
*/
static sanitize(source: string): string;
}
/**
* The internal dialog data for the synchronize dialog.
* Sets default values.
*/
declare class SynchronizeDialogDataInternal implements SynchronizeDialogData {
title: string;
closeButtonLabel: string;
syncAllButtonLabel: string;
undoAllButtonLabel: string;
constructor(data?: SynchronizeDialogData);
}
/**
* The dialog for syncing cached requests to the server.
*/
declare class NgxPwaSynchronizeDialogComponent<OfflineServiceType extends NgxPwaOfflineService> implements OnInit {
readonly offlineService: OfflineServiceType;
readonly sanitizer: DomSanitizer;
private readonly dialogRef;
readonly data: SynchronizeDialogData;
PurifyUtilities: typeof PurifyUtilities;
/**
* The provided dialog data filled up with default values.
*/
dialogData: SynchronizeDialogDataInternal;
constructor(offlineService: OfflineServiceType, sanitizer: DomSanitizer, dialogRef: MatDialogRef<NgxPwaSynchronizeDialogComponent<OfflineServiceType>>, data: SynchronizeDialogData);
ngOnInit(): void;
/**
* Sends a specific cached request to the server.
* @param request - The request that should be synced.
*/
syncSingleRequest(request: CachedRequest<unknown>): Promise<void>;
/**
* Removes a single request from the cache.
* @param request - The request that should be removed.
*/
removeSingleRequest(request: CachedRequest<unknown>): void;
/**
* Sends all cached requests to the server. Tries to handle dependencies of requests on each other.
*/
syncAll(): Promise<void>;
/**
* Removes all locally cached requests.
*/
undoAll(): void;
/**
* Closes the dialog.
*/
close(): void;
static ɵfac: i0.ɵɵFactoryDeclaration<NgxPwaSynchronizeDialogComponent<any>, never>;
static ɵcmp: i0.ɵɵComponentDeclaration<NgxPwaSynchronizeDialogComponent<any>, "ngx-pwa-synchronize-dialog", never, {}, {}, never, never, true, never>;
}
/**
* The data to customize the Version Ready Dialog.
*/
interface VersionReadyDialogData {
/**
* The title of the dialog.
* @default 'New Version downloaded'
*/
title?: string;
/**
* The message to display inside the dialog content.
* @default 'A new version has been downloaded. Do you want to install it now?'
*/
message?: string;
/**
* The label for the button that updates the pwa.
* @default 'Reload'
*/
confirmButtonLabel?: string;
/**
* The label for the button that closes the dialog without updating the pwa.
* @default 'Not now'
*/
cancelButtonLabel?: string;
}
/**
* The internal data to customize the Version Ready Dialog.
* Sets default values.
*/
declare class VersionReadyDialogDataInternal implements VersionReadyDialogData {
title: string;
message: string;
confirmButtonLabel: string;
cancelButtonLabel: string;
constructor(data?: VersionReadyDialogData);
}
/**
* A dialog that gets displayed when a new version of the pwa has been downloaded and is ready for install.
*/
declare class NgxPwaVersionReadyDialogComponent implements OnInit {
private readonly dialogRef;
readonly data?: VersionReadyDialogData | undefined;
/**
* The data to customize the Version Ready Dialog.
* Is built from the MAT_DIALOG_DATA input.
*/
versionReadyDialogData: VersionReadyDialogDataInternal;
constructor(dialogRef: MatDialogRef<NgxPwaVersionReadyDialogComponent>, data?: VersionReadyDialogData | undefined);
ngOnInit(): void;
/**
* Closes the dialog with data to trigger a reload of the app.
*/
update(): void;
/**
* Closes the dialog with data to not trigger anything.
*/
cancel(): void;
static ɵfac: i0.ɵɵFactoryDeclaration<NgxPwaVersionReadyDialogComponent, never>;
static ɵcmp: i0.ɵɵComponentDeclaration<NgxPwaVersionReadyDialogComponent, "ngx-pwa-version-ready-dialog", never, {}, {}, never, never, true, never>;
}
/**
* Some common http methods.
*/
declare enum HttpMethod {
POST = "POST",
GET = "GET",
PATCH = "PATCH",
DELETE = "DELETE"
}
/**
* A base service that provides functionality regarding notifications.
*/
declare abstract class NgxPwaNotificationService {
private readonly swPush;
private readonly http;
/**
* The url to send a new push subscription to.
*/
abstract readonly API_ENABLE_NOTIFICATIONS_URL: string;
/**
* The url to send a request to when wanting to disable notifications.
*/
abstract readonly API_DISABLE_NOTIFICATIONS_URL: string;
/**
* The public key of your VAPID key pair.
* Is needed to receive and display push notifications.
*/
abstract readonly VAPID_PUBLIC_KEY: string;
/**
* Whether or not the current user has notifications enabled.
*/
get hasNotificationsEnabled(): boolean;
constructor(swPush: SwPush, http: HttpClient);
/**
* Asks the user for permission to use push notifications.
*/
askForNotificationPermission(): Promise<void>;
/**
* Enables notifications by sending a push subscription to the server.
* @param pushSubscription - The push subscription to send to the server.
*/
protected enableNotifications(pushSubscription: PushSubscription): Promise<void>;
/**
* Disables notifications.
*/
disableNotifications(): Promise<void>;
}
/**
* An interceptor that caches any POST, UPDATE or DELETE requests when the user is offline.
*/
declare class OfflineRequestInterceptor<OfflineServiceType extends NgxPwaOfflineService> implements HttpInterceptor {
private readonly offlineService;
constructor(offlineService: OfflineServiceType);
intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>>;
private getRequestMetadata;
private requestShouldBeCached;
private requestMethodIsPostPatchOrDelete;
private urlShouldNotBeCached;
static ɵfac: i0.ɵɵFactoryDeclaration<OfflineRequestInterceptor<any>, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<OfflineRequestInterceptor<any>>;
}
/**
* Provides helpers for handling pwa version updates.
*/
declare class NgxPwaUpdateService {
private readonly swUpdate;
private readonly dialog;
constructor(swUpdate: SwUpdate, dialog: MatDialog);
/**
* Subscribes to any version update events.
*/
subscribeToUpdateEvents(): void;
/**
* Gets called when no new version was found.
*/
protected onNoNewVersionDetected(): void;
/**
* Gets called when the installation of a new version fails.
*/
protected onVersionInstallationFailed(): void;
/**
* Gets called when a new version has been found.
*/
protected onVersionDetected(): void;
/**
* Gets called when the version has a critical error.
*/
protected onVersionFailed(): void;
/**
* Gets called when a new version has been installed.
*/
protected onVersionReady(): Promise<void>;
/**
* Manually checks for updates.
* @returns Whether or not new updates are available.
*/
checkForUpdates(): Promise<boolean>;
}
export { HttpMethod, NGX_PWA_HTTP_CONTEXT_METADATA, NGX_PWA_OFFLINE_SERVICE, NgxPwaNotificationService, NgxPwaOfflineService, NgxPwaOfflineStatusBarComponent, NgxPwaSynchronizeBadgeComponent, NgxPwaSynchronizeDialogComponent, NgxPwaUpdateService, NgxPwaVersionReadyDialogComponent, OfflineRequestInterceptor };
export type { BaseEntityType, CachedRequest, RequestMetadata, SynchronizeDialogData, VersionReadyDialogData };