Progressive Web Apps 是漸進式Web應用程序,運行在現代瀏覽器並展示出超級能力。支持可發現,可安裝,離線運行,消息推送等APP特有的能力,本項目以最簡單的方式封裝了消息推送功能在nodejs端的實現。html
KOA2-PWA 是pwa推送服務器的簡單實現,使用 koa2 開發,使用 mysql 數據庫儲存,使用 pm2 管理進程和日誌。前端
查看 PWA前端項目實現node
pwa 消息推送功能依賴於Service Worker(簡稱sw),使用 VAPID 協議。 mysql
-> server端使用 web-push 生成vapidKeys(publicKey,privateKey)
-> server端保存publicKey,privateKey,前端保存publicKey
-> 前端sw使用加密後的publicKey去訂閱並得到訂閱對象,而後保存到server端
-> server端在須要推送時獲取訂閱對象便可推送git
項目目錄中,app.js是啓動文件,/bin/www是啓動文件的封裝,通常使用www啓動服務;
/public是web靜態文件,/views是網頁模板;
重點來看/db和/routes,顯然/db是跟數據庫相關,/routes是跟路由相關。github
// /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 optionsweb
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
複製代碼
githubsql
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
複製代碼