JavaScript を使用したプッシュ通知の実装: 実稼働グレードのアプローチ

WBOY
リリース: 2024-08-17 13:05:02
オリジナル
288 人が閲覧しました

Implementing Push Notifications Using JavaScript: A Production-Grade Approach

この投稿では、本番環境レベルのベスト プラクティスに従って、JavaScript を使用してプッシュ通知を実装する方法を学習します。最も良い点の 1 つは、プロジェクトを簡単にセットアップできるようにフォルダー構造も提供することです。

実際のアプリでプッシュ通知を設定するには、慎重な計画が必要です。プロフェッショナルな Node.js アプリでこの機能を構築する方法を説明します。コードを整理し、安全に保ち、アプリが成長しても確実に動作するようにする方法など、重要な部分について説明します。

始めるには、Node.js サーバーからプッシュ通知を送信するためのライブラリが必要です。 Web プッシュ ライブラリは、通知の送信と必要なキーの管理のためのツールを提供します。

1. プッシュ通知: プロジェクトの構造

まず、クリーンでスケーラブルなコードベースを維持するためにプロジェクト構造をセットアップしましょう:

/notification-service
├── /config
│   ├── default.js
│   └── production.js
├── /controllers
│   └── notificationController.js
├── /models
│   └── user.js
├── /routes
│   └── notificationRoutes.js
├── /services
│   ├── notificationService.js
│   ├── subscriptionService.js
│   └── webPushService.js
├── /utils
│   └── errorHandler.js
├── /tests
│   └── notification.test.js
├── app.js
├── package.json
├── .env
└── README.md
ログイン後にコピー

必要な NPM パッケージ

実装に入る前に、次の NPM パッケージがインストールされていることを確認してください。

  • express: 最小限で柔軟な Node.js Web アプリケーション フレームワーク。
  • mongoose: MongoDB および Node.js 用の ODM (オブジェクト データ モデリング) ライブラリ。
  • web-push: Web プッシュ プロトコルを使用してプッシュ通知を送信するためのライブラリ。
  • dotenv: .env ファイルから環境変数をロードする依存関係のないモジュールです。
  • スーパーテスト: Node.js で HTTP アサーションをテストするためのライブラリ。

npm を使用してこれらのパッケージをインストールします。

bash

npm install express mongoose web-push dotenv supertest
ログイン後にコピー

2. プッシュ通知: プロジェクトの構成

さまざまな環境 (開発、運用など) 用の構成ファイルを作成します。これらのファイルには、環境固有の設定が保存されます。

// /config/default.js
module.exports = {
    server: {
        port: 3000,
        env: 'development'
    },
    pushNotifications: {
        publicVapidKey: process.env.VAPID_PUBLIC_KEY,
        privateVapidKey: process.env.VAPID_PRIVATE_KEY,
        gcmApiKey: process.env.GCM_API_KEY
    },
    db: {
        uri: process.env.MONGO_URI
    }
};
ログイン後にコピー
// /config/production.js
module.exports = {
    server: {
        port: process.env.PORT || 3000,
        env: 'production'
    },
    // Same structure as default, with production-specific values
};
ログイン後にコピー

3. データベースのモデル化

Mongoose を使用して、ユーザー スキーマと通知サブスクリプションを定義します。

// /models/user.js
const mongoose = require('mongoose');

const subscriptionSchema = new mongoose.Schema({
    endpoint: String,
    keys: {
        p256dh: String,
        auth: String
    }
});

const userSchema = new mongoose.Schema({
    email: { type: String, required: true, unique: true },
    subscriptions: [subscriptionSchema],
    preferences: {
        pushNotifications: { type: Boolean, default: true }
    }
});

module.exports = mongoose.model('User', userSchema);
ログイン後にコピー

4. 通知サービス

通知を処理するロジックをモジュール化してサービスに組み込みます。

// /services/webPushService.js
const webPush = require('web-push');
const config = require('config');

webPush.setVapidDetails(
    'mailto:example@yourdomain.org',
    config.get('pushNotifications.publicVapidKey'),
    config.get('pushNotifications.privateVapidKey')
);

module.exports = {
    sendNotification: async (subscription, payload) => {
        try {
            await webPush.sendNotification(subscription, JSON.stringify(payload));
        } catch (error) {
            console.error('Error sending notification', error);
        }
    }
};
ログイン後にコピー
// /services/notificationService.js
const User = require('../models/user');
const webPushService = require('./webPushService');

module.exports = {
    sendPushNotifications: async (userId, payload) => {
        const user = await User.findById(userId);
        if (user && user.preferences.pushNotifications) {
            user.subscriptions.forEach(subscription => {
                webPushService.sendNotification(subscription, payload);
            });
        }
    }
};
ログイン後にコピー

5. コントローラーロジック

API ルートを処理し、サービスを統合します。

// /controllers/notificationController.js
const notificationService = require('../services/notificationService');

exports.sendNotification = async (req, res, next) => {
    try {
        const { userId, title, body } = req.body;
        const payload = { title, body };
        await notificationService.sendPushNotifications(userId, payload);
        res.status(200).json({ message: 'Notification sent successfully' });
    } catch (error) {
        next(error);
    }
};
ログイン後にコピー

6. ルーティング

API のルートを設定します。

// /routes/notificationRoutes.js
const express = require('express');
const router = express.Router();
const notificationController = require('../controllers/notificationController');

router.post('/send', notificationController.sendNotification);

module.exports = router;
ログイン後にコピー

7. エラー処理

エラー処理を一元化して、アプリがクラッシュしないようにします。

// /utils/errorHandler.js
module.exports = (err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send({ error: 'Something went wrong!' });
};
ログイン後にコピー

8. アプリケーションエントリーポイント

アプリケーションを初期化し、データベースに接続します。

// app.js
const express = require('express');
const mongoose = require('mongoose');
const config = require('config');
const notificationRoutes = require('./routes/notificationRoutes');
const errorHandler = require('./utils/errorHandler');

const app = express();

app.use(express.json());
app.use('/api/notifications', notificationRoutes);
app.use(errorHandler);

mongoose.connect(config.get('db.uri'), {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.error('MongoDB connection error:', err));

const PORT = config.get('server.port');
app.listen(PORT, () => console.log(`Server running in ${config.get('server.env')} mode on port ${PORT}`));
ログイン後にコピー

9. セキュリティ慣行

  • 環境変数: API キーやデータベース URI などの機密情報を環境変数に保存します。
  • HTTPS: HTTPS 経由でアプリケーションを提供し、クライアントとサーバー間の通信を保護します。
  • コンテンツ セキュリティ ポリシー (CSP): クロスサイト スクリプティング (XSS) 攻撃を防ぐために CSP ヘッダーを実装します。
  • レート制限: Express-rate-limit などのミドルウェアを使用して、API をブルート フォース攻撃から保護します。

10. テスト

サービスがさまざまな条件下で期待どおりに動作することを確認するテストを作成します。

// /tests/notification.test.js
const request = require('supertest');
const app = require('../app');

describe('Notification API', () => {
    it('should send a notification', async () => {
        const res = await request(app)
            .post('/api/notifications/send')
            .send({ userId: 'someUserId', title: 'Test', body: 'This is a test' });
        expect(res.statusCode).toEqual(200);
        expect(res.body.message).toBe('Notification sent successfully');
    });
});
ログイン後にコピー

11. 本番環境へのデプロイ

  • CI/CD パイプライン: Jenkins、GitHub Actions、GitLab CI などのツールを使用して CI/CD パイプラインをセットアップし、アプリケーションのテスト、構築、デプロイを自動化します。
  • コンテナ化: アプリケーションを Docker 化して、さまざまな環境間での一貫性を確保します。
  • 監視: Prometheus や Grafana などの監視ツールを使用して、アプリケーションの健全性とパフォーマンスを追跡します。

12. スケーリング

  • 水平スケーリング: ロード バランサーの背後にサービスの複数のインスタンスをデプロイして、高トラフィックを処理します。
  • データベース スケーリング: データベースの水平スケーリングのために MongoDB にシャーディングまたはレプリカ セットを実装します。

この運用グレードのセットアップにより、プッシュ通知システムの拡張性、安全性、保守性が保証されます。このコードは、業界のベスト プラクティスに従って、簡単なテスト、展開、監視をサポートするように編成されています。さらに質問がある場合、または具体的な実装の詳細が必要な場合は、お気軽にお問い合わせください。

以上がJavaScript を使用したプッシュ通知の実装: 実稼働グレードのアプローチの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!