aboutsummaryrefslogtreecommitdiffstats
path: root/pages/api/register.js
blob: 56c8ba93d50aced2907a55f19da4cf79c1a5c80d (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
34
35
36
37
38
39
40
import dbConnect from 'configs/dbConnect'
import sendMail from 'configs/sendMail'
import withSession from 'hocs/withSession'
import mailData from 'helpers/email'
import User from 'models/User'
import NoteList from 'apps/Notes/models/NoteList'

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

  switch (req.method) {
    case 'POST':
      try {
        const session = await conn.startSession()

        await session.withTransaction(async () => {
          const noteList = await NoteList.create({})
          const body = JSON.parse(req.body)
          const { _id, email, verificationKey: key, theme, language } = await User.create({ ...body, noteList })

          if (!email) { throw new Error('Something went wrong') }

          sendMail({to: body.email, ...mailData('v', language, key)})

          const user = { _id, email, noteList, theme, language, isVerified: false, isLoggedIn: true }
          req.session.set('user', user)
          await req.session.save()

          session.endSession()
          res.status(201).json(user)
        })
      } catch (error) {
        res.status(400).json({ isLoggedIn: false })
      }
      break
    default:
      res.status(400).json({ isLoggedIn: false })
      break
  }
})