1
1
const router = require ( 'express' ) . Router ( ) ;
2
2
const User = require ( '../model/user' ) ;
3
- const Joi = require ( 'joi' )
3
+ const {
4
+ RegisterValidation
5
+ } = require ( '../validation' ) ;
4
6
5
- const schema = Joi . object ( {
6
- name : Joi . string ( )
7
- . alphanum ( )
8
- . min ( 3 )
9
- . max ( 30 )
10
- . required ( ) ,
11
- password : Joi . string ( )
12
- . pattern ( new RegExp ( '^[a-zA-Z0-9]{3,30}$' ) ) ,
13
- repeat_password : Joi . ref ( 'password' ) ,
14
- email : Joi . string ( )
15
- . email ( { minDomainSegments : 2 , tlds : { allow : [ 'com' , 'net' ] } } )
16
-
17
-
18
- } ) ;
19
7
router . post ( '/register' , async ( req , res ) => {
20
8
// Validate the data before we make a user
21
- const { error } = schema . validate ( req . body ) ;
22
- if ( error ) return res . status ( 400 ) . send ( error . details [ 0 ] . message ) ;
23
- const user = new User ( {
24
- name : req . body . name ,
25
- email : req . body . email ,
26
- password : req . body . password ,
27
- date : req . body . date
9
+ const {
10
+ error
11
+ } = RegisterValidation ( req . body ) ;
12
+ if ( error ) return res . status ( 400 ) . send ( error . details [ 0 ] . message ) ;
13
+ //create new user
14
+ const emailExist = await User . findOne ( {
15
+ email : req . body . email
28
16
} ) ;
29
- try {
17
+ if ( emailExist ) return res . status ( 400 ) . send ( 'Email already exists' ) ;
18
+
19
+ const user = new User ( {
20
+ name : req . body . name ,
21
+ email : req . body . email ,
22
+ password : req . body . password ,
23
+ date : req . body . date
24
+ } ) ;
25
+ try {
26
+ //save user to MongoDB
30
27
const savedUser = await user . save ( ) ;
31
28
res . send ( savedUser ) ;
32
- } catch ( err ) {
33
- res . status ( 400 ) . send ( err ) ;
34
- }
35
-
29
+ } catch ( err ) {
30
+ //res.status in case of error
31
+ res . status ( 400 ) . send ( err ) ;
32
+ }
33
+
36
34
} ) ;
37
35
38
36
module . exports = router ;
0 commit comments