push-уведомление с угловым и nodejs - PullRequest
0 голосов
/ 03 декабря 2018

У меня есть push-уведомление с angular и nodejs ... Когда я действую статью, я отправлю push-уведомление пользователю, создаст статью ... User1 создаст статью, и когда администратор подтвердит действие этой статьи, user1 получит уведомление ... это мой кодв общем для получения уведомления, но где модификация в моем коде для получения уведомления только для пользователя 1.

код службы угловой:

import { Injectable } from '@angular/core';
        import { HttpClient } from '@angular/common/http';

        const SERVER_URL = 'http://localhost:3000/subscription';

        @Injectable()
        export class PushNotificationService {
          constructor(private http: HttpClient) {}

          public sendSubscriptionToTheServer(subscription: PushSubscription) {
            return this.http.post(SERVER_URL, subscription);
          }
        }

код компонента:

import { Component, OnInit } from '@angular/core';
    import { SwPush } from '@angular/service-worker';
    import { PushNotificationService } from '../../services/push-notification.service';

    const VAPID_PUBLIC = "BJPrg7jbhWkWZn5mhg0Wti8031cHjsLGyN1G4pmfeippmEsXHo53wnRiqqjApVkA1KQyIz0IYK4ln0ie7RLrsiI";
    const PRIVATE = "D1njq6Y7ny2QexJ-JZXbUpufCkfIywLSMvO6s-iSNoQ";

    @Component({
      selector: 'app-test-component',
      templateUrl: './test-component.component.html',
      styleUrls: ['./test-component.component.scss']
    })
    export class TestComponentComponent implements OnInit {

       constructor(public swPush: SwPush, public pushService: PushNotificationService) {

       }

        test(){
             if (this.swPush.isEnabled) {
              this.swPush
                .requestSubscription({
                  serverPublicKey: VAPID_PUBLIC
                })
                .then(subscription => {
                    this.pushService.sendSubscriptionToTheServer(subscription).subscribe();
                })
                .catch(console.error);
            }
       }

      ngOnInit() {
      }

    }

код nodejs:

const express = require('express');
const webpush = require('web-push');
const cors = require('cors');
const bodyParser = require('body-parser');

const PUBLIC_VAPID = 'BJPrg7jbhWkWZn5mhg0Wti8031cHjsLGyN1G4pmfeippmEsXHo53wnRiqqjApVkA1KQyIz0IYK4ln0ie7RLrsiI';
const PRIVATE_VAPID = 'D1njq6Y7ny2QexJ-JZXbUpufCkfIywLSMvO6s-iSNoQ';

const fakeDatabase = [];

const app = express();

app.use(cors());
app.use(bodyParser.json());

webpush.setVapidDetails('mailto:mailto@gmail.com', PUBLIC_VAPID, PRIVATE_VAPID);

app.post('/subscription', (req, res) => {
  const subscription = req.body;
  fakeDatabase.push(subscription);

  const notificationPayload = {
    notification: {
      title: 'New Notification',
      body: 'This is the body of the notification',
      icon: 'assets/icons/icon-512x512.png'
    }
  };

  const promises = [];
  fakeDatabase.forEach(subscription => {
    promises.push(webpush.sendNotification(subscription, JSON.stringify(notificationPayload)));
  });
  fakeDatabase.length =0
  Promise.all(promises).then(() => res.sendStatus(200));
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

помогите мне и спасибо за продвинутый

...