Skip to content

Commit cab13d3

Browse files
Moved post insertion & subscription notifications into lib/reddit.ts.
1 parent db57349 commit cab13d3

File tree

2 files changed

+81
-46
lines changed

2 files changed

+81
-46
lines changed
Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { NextRequest, NextResponse } from 'next/server'
2-
import { fetchRedditPosts } from '@/lib/reddit'
2+
import { fetchRedditPosts, storePosts } from '@/lib/reddit'
33
import webpush from 'web-push'
4-
import { sendNotification } from '@/lib/notifications'
54
import prisma from '@/lib/db'
65

76
// List of subreddits to monitor for new posts
@@ -23,51 +22,16 @@ webpush.setVapidDetails(
2322

2423
export async function GET(req: NextRequest) {
2524
try {
26-
// Fetch posts from the specified subreddits
2725
const posts = await fetchRedditPosts(SUBREDDITS)
26+
const hiringPosts = posts.filter((post) => post.title.includes('[Hiring]'))
2827

29-
// Retrieve all subscriptions for sending notifications
30-
const subscriptions = await prisma.subscription.findMany()
28+
await storePosts(hiringPosts)
3129

32-
for (const post of posts) {
33-
// Check if the post is marked with '[Hiring]'
34-
if (!post.title.includes('[Hiring]')) continue
35-
36-
// Ensure the post is not already in the database
37-
const existingPost = await prisma.post.findUnique({
38-
where: { url: post.url },
39-
})
40-
if (existingPost) continue
41-
42-
// Add the post to the database if it's new
43-
const createdPost = await prisma.post.create({ data: post })
44-
45-
// 2. Build your unified payload object
46-
const notificationPayload = {
47-
title: `${createdPost.title} (${createdPost.subreddit} - ${createdPost.author})`,
48-
body: `${createdPost.title}`,
49-
url: createdPost.url,
50-
icon: 'https://new.codebuilder.org/images/logo2.png',
51-
badge: 'https://new.codebuilder.org/images/logo2.png',
52-
}
53-
54-
// 3. Loop and send notifications concurrently
55-
const notificationPromises = subscriptions.map((sub) =>
56-
sendNotification(sub, notificationPayload)
57-
)
58-
59-
// 4. Wait for all notifications to complete
60-
await Promise.all(notificationPromises)
61-
}
62-
63-
// Respond with success if posts fetched and processed successfully
6430
return NextResponse.json({ message: 'Posts fetched and stored successfully.' })
6531
} catch (error) {
66-
// Log any errors and respond with a 500 status code
67-
console.log(error) //error()
32+
console.error(error)
6833
return NextResponse.json({ error: 'An error occurred while fetching posts.' }, { status: 500 })
6934
} finally {
70-
// Ensure the Prisma client is disconnected after execution
7135
await prisma.$disconnect()
7236
}
7337
}

src/lib/reddit.ts

Lines changed: 77 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ import axios from 'axios'
44
import Snoowrap from 'snoowrap'
55
import { PrismaClient } from '@prisma/client'
66
import { CommentStream } from 'snoostorm'
7-
8-
const prisma = new PrismaClient()
7+
import { sendNotification } from './notifications'
8+
import prisma from '@/lib/db'
99

1010
// Initialize Reddit API client with environment variables
1111
export const redditClient = new Snoowrap({
12-
userAgent: 'your-app-name by /u/your-username',
12+
userAgent: 'CodeBuilder by /u/taofullstack',
1313
clientId: process.env.REDDIT_CLIENT_ID,
1414
clientSecret: process.env.REDDIT_CLIENT_SECRET,
1515
username: process.env.REDDIT_USERNAME,
@@ -25,6 +25,9 @@ export async function storeMessages(items: Array<Snoowrap.PrivateMessage | Snoow
2525
const newMessages = []
2626
console.debug(`Processing ${items.length} message(s)`)
2727

28+
// Retrieve all subscriptions for sending notifications
29+
const subscriptions = await prisma.subscription.findMany()
30+
2831
for (const item of items) {
2932
try {
3033
const isMessage = item instanceof Snoowrap.PrivateMessage
@@ -64,12 +67,29 @@ export async function storeMessages(items: Array<Snoowrap.PrivateMessage | Snoow
6467
contextUrl: item.permalink,
6568
}
6669

67-
const created = await prisma.redditMessage.create({
70+
const createdMsg = await prisma.redditMessage.create({
6871
data: { ...baseData, ...additionalData },
6972
})
7073

71-
console.debug(`Stored new ${type} [${created.redditId}] from /u/${created.author}`)
72-
newMessages.push(created)
74+
// Build your unified payload object
75+
const notificationPayload = {
76+
title: `${createdMsg.author} (${createdMsg.subreddit})`,
77+
body: `${createdMsg.content}`,
78+
url: createdMsg.contextUrl,
79+
icon: 'https://new.codebuilder.org/images/logo2.png',
80+
badge: 'https://new.codebuilder.org/images/logo2.png',
81+
}
82+
83+
// Loop and send notifications concurrently
84+
const notificationPromises = subscriptions.map((sub) =>
85+
sendNotification(sub, notificationPayload)
86+
)
87+
88+
// Wait for all notifications to complete
89+
await Promise.all(notificationPromises)
90+
91+
console.debug(`Stored new ${type} [${createdMsg.redditId}] from /u/${createdMsg.author}`)
92+
newMessages.push(createdMsg)
7393
} catch (error) {
7494
console.error(`Error processing message ${item.name}:`, error.message)
7595
}
@@ -161,3 +181,54 @@ export const fetchRedditPosts = async (subreddits: string[]) => {
161181

162182
return posts
163183
}
184+
185+
/**
186+
* Stores Reddit posts in database with deduplication and sends notifications
187+
* @param posts Array of Reddit post objects
188+
* @returns Array of newly created database records
189+
*/
190+
export async function storePosts(posts: Array<any>) {
191+
const newPosts = []
192+
console.debug(`Processing ${posts.length} post(s)`)
193+
194+
// Retrieve all subscriptions for sending notifications
195+
const subscriptions = await prisma.subscription.findMany()
196+
197+
for (const post of posts) {
198+
try {
199+
// Check for existing record
200+
const existing = await prisma.post.findUnique({
201+
where: { url: post.url },
202+
})
203+
204+
if (existing) {
205+
console.debug(`Skipping duplicate post [${post.url}]`)
206+
continue
207+
}
208+
209+
const createdPost = await prisma.post.create({ data: post })
210+
211+
// Build notification payload
212+
const notificationPayload = {
213+
title: `${createdPost.title} (${createdPost.subreddit} - ${createdPost.author})`,
214+
body: `${createdPost.title}`,
215+
url: createdPost.url,
216+
icon: 'https://new.codebuilder.org/images/logo2.png',
217+
badge: 'https://new.codebuilder.org/images/logo2.png',
218+
}
219+
220+
// Send notifications concurrently
221+
const notificationPromises = subscriptions.map((sub) =>
222+
sendNotification(sub, notificationPayload)
223+
)
224+
await Promise.all(notificationPromises)
225+
226+
console.debug(`Stored new post [${createdPost.url}] from /u/${createdPost.author}`)
227+
newPosts.push(createdPost)
228+
} catch (error) {
229+
console.error(`Error processing post ${post.url}:`, error.message)
230+
}
231+
}
232+
233+
return newPosts
234+
}

0 commit comments

Comments
 (0)