1+ import express from 'express' ;
2+ import { check , validationResult } from 'express-validator' ;
3+ import { validate } from 'deep-email-validator' ;
4+ import User from '../models/user.js' ;
5+ 6+ const validateEmail = express . Router ( ) ;
7+ 8+ validateEmail . use ( express . json ( ) ) ;
9+ validateEmail . use ( express . urlencoded ( { extended : true } ) ) ;
10+ 11+ const rules = [
12+ check ( 'email' ) . trim ( ) . toLowerCase ( ) . notEmpty ( ) . escape ( ) . isEmail ( ) . normalizeEmail ( ) . custom ( async ( email ) => {
13+ const valid = ( await validate ( email ) ) . valid ;
14+ 15+ if ( ! valid ) throw new Error ( `${ email } doesn't exist, Please Enter a valid Email.` ) ;
16+ } ) ,
17+ ] ;
18+ 19+ const checkEmail = ( req , res , next ) => {
20+ const error = validationResult ( req ) ;
21+ 22+ if ( ! error . isEmpty ( ) ) return res . status ( 200 ) . send ( { 'valid' : false , 'found' : false } ) ; else next ( ) ;
23+ } ;
24+ 25+ const findUser = async ( req , res , next ) => {
26+ const email = ( req . query . email ? req . query . email : req . body . email ) ;
27+ 28+ const user = await User . findOne ( { 'email' : email } , { '_id' : 1 } ) ;
29+ 30+ if ( user ) return res . status ( 200 ) . send ( { 'valid' : true , 'found' : true } ) ;
31+ else next ( ) ;
32+ } ;
33+ 34+ // const middleware = [ rules, checkEmail, findUser ];
35+ 36+ const middleware = [ findUser ] ;
37+ 38+ validateEmail . get ( '/' , middleware , ( req , res ) => {
39+ res . status ( 200 ) . send ( { 'valid' : true , 'found' : false } ) ;
40+ } ) ;
41+ 42+ validateEmail . post ( '/' , middleware , ( req , res ) => {
43+ res . status ( 200 ) . send ( { 'valid' : true , 'found' : false } ) ;
44+ } ) ;
45+ 46+ export default validateEmail ;
0 commit comments