Skip to content

Commit

Permalink
Added contact-stats collection (#67)
Browse files Browse the repository at this point in the history
* added contact-stat schema

* added API endpoints for contact-stats
  • Loading branch information
mai-vu authored May 22, 2024
1 parent 28d9e9f commit fefdb22
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 0 deletions.
115 changes: 115 additions & 0 deletions src/app/api/contact-stat/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { NextResponse } from 'next/server';
import { connectMongoDB } from '@/libs/mongodb';
import contactStat from '@/app/api/contactStat';
import mongoose from 'mongoose';

export async function GET() {
try {
await connectMongoDB();

const ContactStat =
mongoose.models['contact-stats'] ||
mongoose.model('contact-stats', contactStat);

const contactStats = await ContactStat.find();

return NextResponse.json({ contactStats }, { status: 200 });
} catch (error) {
console.error('Error fetching contact stats:', error);
return NextResponse.json(
{ message: 'Failed to fetch contact stats' },
{ status: 500 }
);
}
}

export async function POST(req) {
try {
const emailAddresses = await req.json();

if (!Array.isArray(emailAddresses)) {
return NextResponse.json(
{ message: 'Bad Request - Email addresses must be an array' },
{ status: 400 }
);
}

let newEmailAddresses = [];

//if emailAddresses is not empty, add non duplicate email addresses to the contactStat collection
if (emailAddresses.length > 0) {
await connectMongoDB();
const ContactStat =
mongoose.models['contact-stats'] ||
mongoose.model('contact-stats', contactStat);

// Get all email addresses from the contactStat collection
const existingEmailAddresses = await ContactStat.find({}, { email: 1 });

// Filter out email addresses that are not already in the contactStat collection
newEmailAddresses = emailAddresses.filter(
({ email }) =>
!existingEmailAddresses.some(
existingEmail => existingEmail.email === email
)
);

// Insert email addresses into the contactStat collection
await ContactStat.insertMany(newEmailAddresses);
}

//return total number of email addresses added and status code 200
return NextResponse.json(
{ message: `Added ${newEmailAddresses.length} email addresses` },
{ status: 200 }
);
} catch (error) {
console.error('Error inserting contact stats:', error);
return NextResponse.json(
{ message: 'Failed to insert contact stats' },
{ status: 500 }
);
}
}

export async function PATCH(req) {
try {
const { email, sent } = await req.json();

if (!email) {
return NextResponse.json(
{ message: 'Bad Request - Email parameter is required' },
{ status: 400 }
);
}

await connectMongoDB();

const ContactStat =
mongoose.models['contact-stats'] ||
mongoose.model('contact-stats', contactStat);

const updatedContactStat = await ContactStat.updateOne(
{ email },
{ $set: { sent: sent !== undefined ? sent : true } }
);

if (updatedContactStat.nModified === 0) {
return NextResponse.json(
{ message: 'No contact stats were updated' },
{ status: 404 }
);
}

return NextResponse.json(
{ message: 'Contact stats updated successfully' },
{ status: 200 }
);
} catch (error) {
console.error('Error updating contact stats:', error);
return NextResponse.json(
{ message: 'Failed to update contact stats' },
{ status: 500 }
);
}
}
5 changes: 5 additions & 0 deletions src/app/api/contactStat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import mongoose from 'mongoose';
export default new mongoose.Schema({

Check warning on line 2 in src/app/api/contactStat.js

View workflow job for this annotation

GitHub Actions / format

Assign instance to a variable before exporting as module default
email: { type: String, required: true },
sent: Boolean,
});

0 comments on commit fefdb22

Please sign in to comment.