Created
November 30, 2014 14:42
-
-
Save jhenriquez/3cb5d382b699b1bbfd8b to your computer and use it in GitHub Desktop.
Doctor's Signup API Post Request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'), | |
UserService = require('../../services/UserService'), | |
SubscriptionService = require('../../services/SubscriptionService'), | |
Joi = require('joi'), | |
joiful = require('../../lib/joiful'), | |
router = express.Router(); | |
var SignupDoctorPostSchema = Joi.object().keys({ | |
username: Joi.string().required(), | |
email: Joi.string().email().required(), | |
password: Joi.string().required(), | |
plan: Joi.string().required() | |
}).required(); | |
function SignupDoctorPostRequest(data) { | |
this.validatePlanId = function() { | |
return SubscriptionService.hasValidPlan(data.plan); | |
}; | |
this.createUser = function () { | |
return UserService.save(data); | |
}; | |
this.subscribeUser = function () { | |
return SubscriptionService.create(data); | |
}; | |
} | |
router.post('/', function (rq, response) { | |
var validation = SignupDoctorPostSchema.validate(rq.body); | |
if(validation.error) { | |
response. | |
status(422). | |
json({ | |
status: 'fail', | |
data: joiful.parseValidationError(validation.error) | |
}); | |
return; | |
} | |
var request = new SignupDoctorPostRequest(validation.value); | |
request.validatePlanId() | |
.then(request.createUser) | |
.then(request.subscribeUser) | |
.then( | |
function Success (authenticatedUser) { | |
response.status(201).json({}); | |
} | |
) | |
.catch( | |
function Fail (fail) { | |
var statusCode = fail.type === 'Validation' ? 422 : 500; | |
var responseStatus = fail.type === 'Validation' ? 'fail' : 'error'; | |
var responseData = fail.type === 'Validation' ? fail.details : fail.message; | |
response. | |
status(statusCode). | |
json({ | |
status: responseStatus, | |
data: responseData | |
}); | |
} | |
); | |
}); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment