You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const Question = require('../../../models/question');
  2. import dbConnect from '../../../utils/helpers/dbHelpers';
  3. const sgMail = require('@sendgrid/mail');
  4. import type { NextApiRequest, NextApiResponse } from 'next';
  5. import {
  6. QuestionDataDB,
  7. QuestionResponse,
  8. } from '../../../utils/interface/questionInterface';
  9. async function handler(
  10. req: NextApiRequest,
  11. res: NextApiResponse<QuestionResponse>
  12. ) {
  13. const { method } = req;
  14. await dbConnect();
  15. switch (method) {
  16. case 'POST': {
  17. try {
  18. const question: QuestionDataDB = await Question.create(req.body);
  19. sgMail.setApiKey(process.env.NEXT_PUBLIC_SEND_GRID);
  20. const msg = {
  21. to: '[email protected]', //req.body.email, // Change to your recipient
  22. from: '[email protected]', // Change to your verified sender
  23. subject: 'Question submitted',
  24. text: 'Your question was submitted successfully, we will contact you via email shortly. Thank you!',
  25. html: '<strong>Your question was submitted successfully, we will contact you via email shortly. Thank you!</strong>',
  26. };
  27. sgMail.send(msg).then(() => {
  28. console.log('Email sent');
  29. });
  30. res.status(201).json({
  31. message:
  32. 'Your message/question was submitted successfully, check your mail for confirmation.',
  33. question,
  34. });
  35. } catch (error) {
  36. if (error instanceof Error)
  37. res.status(400).json({ message: error.message });
  38. else res.status(400).json({ message: 'Unexpected error' + error });
  39. }
  40. break;
  41. }
  42. default:
  43. res.status(405).json({ message: 'Method not allowed' });
  44. break;
  45. }
  46. }
  47. export default handler;