概念
Progressive web Apps 是渐进式 Web 应用程序, 运行在现代浏览器并展现出超级能力支持可发现, 可安装, 离线运行, 消息推送等 APP 特有的能力, 本项目以最简单的方式封装了消息推送功能在 nodejs 端的实现
KOA2-PWA
KOA2-PWA 是 pwa 推送服务器的简单实现, 使用 koa2 开发, 使用 mysql 数据库储存, 使用 pm2 管理进程和日志
查看 PWA 前端项目实现 https://github.com/chesscai/simple-pwa
运行过程
pwa 消息推送功能依赖于 Service Worker(简称 sw), 使用 VAPID 协议
notification
-> server 端使用 web-push 生成 vapidKeys(publicKey,privateKey)
-> server 端保存 publicKey,privateKey, 前端保存 publicKey
-> 前端 sw 使用加密后的 publicKey 去订阅并获得订阅对象, 然后保存到 server 端
-> server 端在需要推送时获取订阅对象即可推送
项目目录中, app.js 是启动文件,/bin/www 是启动文件的封装, 一般使用 www 启动服务;
/public 是 web 静态文件,/views 是网页模板;
重点来看 / db 和 / routes, 显然 / db 是跟数据库相关,/routes 是跟路由相关
- // /db/config.js 保存数据库登录信息
- const config = {
- host: ***,
- user: ***,
- password: ***,
- database: '***', // 数据库名称, 自定义
- port: ***
- }
- module.exports = config
- // /db/index.js 数据库相关操作
- const mysql = require('mysql')
- const config = require('./config')
- const pool = mysql.createPool(config)
- // some sql
- module.exports = {
- // some methods
- }
- /routes/notification.js:
更多推送消息配置项 Notification options
- const router = require('koa-router')()
- const webpush = require('web-push')
- const dbModel = require('../db/index')
- // VAPID keys should only be generated only once.
- // const vapidKeys = webpush.generateVAPIDKeys()
- const publicKey = '***'
- const privateKey = '***'
- const gcmapiKey = 'PWA_LITE_GCMAPIKey' // 自定义, 保存在前端 manifest.json
- const mailto = 'mailto:yourname@mail.com'
- // send notification to client
- const sendNotification = (pushSubscription, body) => {
- return webpush.sendNotification(pushSubscription, JSON.stringify(body))
- }
- webpush.setGCMAPIKey(gcmapiKey)
- webpush.setVapidDetails(mailto, publicKey, privateKey)
- // router prefix
- router.prefix('/api/notification')
- // user subscribe
- router.post('/subscribe', async (ctx, next) => {
- let body = ctx.request.body
- let user = [body.authSecret, body.key, body.endpoint]
- let pushSubscription = {
- endpoint: body.endpoint,
- keys: {
- auth: body.authSecret,
- p256dh: body.key
- }
- }
- let body = {
- title: 'Congratulations',
- message: `Hello,Thank you for subscribtion!`,
- data: {}
- }
- sendNotification(pushSubscription, body)
- // do something
- })
- module.exports = router
开始
github https://github.com/chesscai/koa2-pwa
koa2 需要 nodejs 7.6 以上版本
- # install pm2
- npm install -g pm2
- # install dependencies
- npm install
- # serve with hot reload at localhost:3000
- npm start
- # run with pm2
- npm run prd
- # or pm2 start bin/www
来源: https://juejin.im/post/5aa0ffa5f265da23a04921e8