mirror of
https://github.com/xtr-dev/payload-notifications.git
synced 2025-12-10 02:43:23 +00:00
Refactor: Simplify notifications plugin
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -47,3 +47,4 @@ yarn-error.log*
|
||||
/playwright-report/
|
||||
/blob-report/
|
||||
/playwright/.cache/
|
||||
/dev.db
|
||||
|
||||
@@ -75,27 +75,8 @@ export default function DemoPage() {
|
||||
setLoading(true)
|
||||
try {
|
||||
await pushManager.unsubscribe()
|
||||
|
||||
// Remove the subscription from Payload's database
|
||||
const response = await fetch('/api/push-notifications/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
user: 'customer@example.com', // Associate with the demo customer user
|
||||
}),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
setIsSubscribed(false)
|
||||
alert('Successfully unsubscribed from push notifications')
|
||||
} else {
|
||||
const error = await response.text()
|
||||
console.warn('Failed to remove subscription from database:', error)
|
||||
setIsSubscribed(false)
|
||||
alert('Unsubscribed from browser, but may still be in database')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to unsubscribe:', error)
|
||||
alert('Failed to unsubscribe from push notifications: ' + (error as Error).message)
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { EmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
/**
|
||||
* Logs all emails to stdout
|
||||
*/
|
||||
export const testEmailAdapter: EmailAdapter<void> = ({ payload }) => ({
|
||||
name: 'test-email-adapter',
|
||||
defaultFromAddress: 'dev@payloadcms.com',
|
||||
defaultFromName: 'Payload Test',
|
||||
sendEmail: async (message) => {
|
||||
const stringifiedTo = getStringifiedToAddress(message)
|
||||
const res = `Test email to: '${stringifiedTo}', Subject: '${message.subject}'`
|
||||
payload.logger.info({ content: message, msg: res })
|
||||
return Promise.resolve()
|
||||
},
|
||||
})
|
||||
|
||||
function getStringifiedToAddress(message: SendEmailOptions): string | undefined {
|
||||
let stringifiedTo: string | undefined
|
||||
|
||||
if (typeof message.to === 'string') {
|
||||
stringifiedTo = message.to
|
||||
} else if (Array.isArray(message.to)) {
|
||||
stringifiedTo = message.to
|
||||
.map((to: { address: string } | string) => {
|
||||
if (typeof to === 'string') {
|
||||
return to
|
||||
} else if (to.address) {
|
||||
return to.address
|
||||
}
|
||||
return ''
|
||||
})
|
||||
.join(', ')
|
||||
} else if (message.to?.address) {
|
||||
stringifiedTo = message.to.address
|
||||
}
|
||||
return stringifiedTo
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import { mongooseAdapter } from '@payloadcms/db-mongodb'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import path from 'path'
|
||||
import { buildConfig } from 'payload'
|
||||
import sharp from 'sharp'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
import {testEmailAdapter} from "./helpers/testEmailAdapter"
|
||||
import {seed} from "./seed"
|
||||
import { notificationsPlugin } from '@xtr-dev/payload-notifications'
|
||||
import {sqliteAdapter} from "@payloadcms/db-sqlite"
|
||||
|
||||
const filename = fileURLToPath(import.meta.url)
|
||||
const dirname = path.dirname(filename)
|
||||
@@ -16,20 +16,7 @@ if (!process.env.ROOT_DIR) {
|
||||
process.env.ROOT_DIR = dirname
|
||||
}
|
||||
|
||||
const buildConfigWithMemoryDB = async () => {
|
||||
if (!process.env.DATABASE_URI) {
|
||||
// Use a simple memory server instead of replica set for better stability
|
||||
const { MongoMemoryServer } = await import('mongodb-memory-server')
|
||||
const memoryDB = await MongoMemoryServer.create({
|
||||
instance: {
|
||||
dbName: 'payloadmemory',
|
||||
},
|
||||
})
|
||||
|
||||
process.env.DATABASE_URI = memoryDB.getUri()
|
||||
}
|
||||
|
||||
return buildConfig({
|
||||
export default buildConfig({
|
||||
admin: {
|
||||
importMap: {
|
||||
baseDir: path.resolve(dirname),
|
||||
@@ -67,12 +54,12 @@ const buildConfigWithMemoryDB = async () => {
|
||||
],
|
||||
},
|
||||
],
|
||||
db: mongooseAdapter({
|
||||
ensureIndexes: true,
|
||||
url: process.env.DATABASE_URI || '',
|
||||
db: sqliteAdapter({
|
||||
client: {
|
||||
url: process.env.DATABASE_URI || 'file:./dev.db',
|
||||
},
|
||||
}),
|
||||
editor: lexicalEditor(),
|
||||
email: testEmailAdapter,
|
||||
onInit: async (payload) => {
|
||||
await seed(payload)
|
||||
},
|
||||
@@ -154,6 +141,3 @@ const buildConfigWithMemoryDB = async () => {
|
||||
outputFile: path.resolve(dirname, 'payload-types.ts'),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export default buildConfigWithMemoryDB()
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
],
|
||||
"compilerOptions": {
|
||||
"baseUrl": "./",
|
||||
"rootDir": "../",
|
||||
"paths": {
|
||||
"@payload-config": [
|
||||
"./payload.config.ts"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xtr-dev/payload-notifications",
|
||||
"version": "0.0.1",
|
||||
"version": "0.0.2",
|
||||
"description": "A PayloadCMS plugin that adds a configurable notifications collection for sending messages with titles, content, and attachable relationship items",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
||||
@@ -188,9 +188,9 @@ export function createNotificationsCollection(options: NotificationsPluginOption
|
||||
return
|
||||
}
|
||||
|
||||
let recipientId: string
|
||||
let recipientId: string|number
|
||||
|
||||
if (typeof doc.recipient === 'string') {
|
||||
if (typeof doc.recipient === 'string' || typeof doc.recipient === 'number') {
|
||||
recipientId = doc.recipient
|
||||
} else if (doc.recipient?.id) {
|
||||
recipientId = doc.recipient.id
|
||||
|
||||
@@ -36,7 +36,7 @@ export function createPushNotificationEndpoints(options: NotificationsPluginOpti
|
||||
|
||||
const pushManager = new WebPushManager(webPushConfig, req.payload)
|
||||
await pushManager.subscribe(
|
||||
String(req.user.id),
|
||||
req.user.id,
|
||||
subscription,
|
||||
userAgent,
|
||||
channels
|
||||
|
||||
@@ -57,7 +57,7 @@ export class WebPushManager {
|
||||
* Send push notification to all active subscriptions for a recipient
|
||||
*/
|
||||
public async sendToRecipient(
|
||||
recipientId: string,
|
||||
recipientId: string|number,
|
||||
title: string,
|
||||
body: string,
|
||||
options?: {
|
||||
@@ -186,7 +186,7 @@ export class WebPushManager {
|
||||
* Subscribe a user to push notifications
|
||||
*/
|
||||
public async subscribe(
|
||||
userId: string,
|
||||
userId: string | number,
|
||||
subscription: PushSubscription,
|
||||
userAgent?: string,
|
||||
channels?: string[]
|
||||
@@ -216,15 +216,6 @@ export class WebPushManager {
|
||||
},
|
||||
})
|
||||
} else {
|
||||
console.info({
|
||||
user: userId,
|
||||
endpoint: subscription.endpoint,
|
||||
p256dh: subscription.keys.p256dh,
|
||||
auth: subscription.keys.auth,
|
||||
userAgent,
|
||||
channels,
|
||||
isActive: true,
|
||||
})
|
||||
// Create new subscription
|
||||
await this.payload.create({
|
||||
collection: 'push-subscriptions',
|
||||
|
||||
Reference in New Issue
Block a user