openaire-library/notifications/notification.service.ts

55 lines
2.1 KiB
TypeScript

import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {properties} from "../../../environments/environment";
import {Observable} from "rxjs";
import {Notification, NotificationUser} from "./notifications";
import {CustomOptions} from "../services/servicesUtils/customOptions.class";
import {not} from "rxjs/internal-compatibility";
import {map} from "rxjs/operators";
@Injectable({
providedIn: "root"
})
export class NotificationService {
constructor(private httpClient: HttpClient) {
}
public getAllNotifications(): Observable<Notification[]> {
return this.httpClient.get<Notification[]>(properties.notificationsAPIURL + 'all', CustomOptions.registryOptions()).pipe(map(notifications => {
notifications.forEach(notification => {
this.formatNotification(notification);
})
return notifications;
}));
}
public getNotifications(service: string): Observable<Notification[]> {
return this.httpClient.get<Notification[]>(properties.notificationsAPIURL + encodeURIComponent(service), CustomOptions.registryOptions()).pipe(map(notifications => {
notifications.forEach(notification => {
this.formatNotification(notification);
})
return notifications;
}));
}
public sendNotification(notification: Notification): Observable<Notification> {
return this.httpClient.post<Notification>(properties.notificationsAPIURL + 'save', notification, CustomOptions.registryOptions());
}
public readNotification(id: string): Observable<NotificationUser> {
return this.httpClient.put<NotificationUser>(properties.notificationsAPIURL + encodeURIComponent(id), null, CustomOptions.registryOptions());
}
private formatNotification(notification: Notification): Notification {
if (notification.title) {
notification.preview = notification.title;
} else {
notification.preview = notification.message.replace(/<[^>]*>/g, '');
notification.preview = notification.preview.replace(/(\r\n|\n|\r| +(?= ))|\s\s+/gm, " ");
}
return notification;
}
}