aboutsummaryrefslogtreecommitdiffstats
path: root/pages/api/register.js
blob: 036cede568ffa0cdf84bc7c28efe8722296c121d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import dbConnect from 'configs/dbConnect'
import sendMail from 'configs/sendMail'
import withSession from 'hocs/withSession'
import { subject, text, html } from 'helpers/email'
import User from 'models/User'
import NoteList from 'models/NoteList'

export default withSession(async (req, res) => {
  await dbConnect()

  switch (req.method) {
    case 'POST':
      try {
        const noteList = await NoteList.create({})

        const { _id, email, verificationKey: key, theme, language } = await User.create({ ...req.body, noteList })
        if (!email) { throw new Error('Something went wrong') }

        sendMail(req.body.email, subject(language), text(language, key), html(language, key))

        const user = { _id, email, noteList, theme, language, isVerified: false, isLoggedIn: true }
        req.session.set('user', user)
        await req.session.save()
        res.status(201).json(user)
      } catch (error) {
        res.status(400).json({ isLoggedIn: false })
      }
      break
    default:
      res.status(400).json({ isLoggedIn: false })
      break
  }
})