Last active
August 29, 2015 14:13
-
-
Save leongaban/6db44e513db4ca9e784f to your computer and use it in GitHub Desktop.
server.js routes api
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
// load the express package and create our app | |
// CALL THE PACKAGES -------------------- | |
var express = require('express'); // call express | |
var app = express(); // define our app using express | |
var bodyParser = require('body-parser'); // get body-parser | |
var morgan = require('morgan'); // used to see requests | |
var mongoose = require('mongoose'); // for working w/ our database | |
var port = process.env.PORT || 8615; // set the port for our app | |
// BASE SETUP | |
// ========================== | |
var User = require('./app/models/user'); | |
// APP CONFIGURATION ---------------------------- | |
// use body parser so we can grab information from POST requests | |
app.use(bodyParser.urlencoded({ extended: true })); | |
app.use(bodyParser.json()); | |
// configure our app to handle CORS requests | |
app.use(function(req, res, next) { | |
res.setHeader('Access-Control-Allow-Origin', '*'); | |
res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); | |
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, \ Authorization'); | |
next(); | |
}); | |
// log all requests to the console | |
app.use(morgan('dev')); | |
// MongoDB connect | |
// mongoose.connect('mongodb://localhost/test'); // local test db | |
mongoose.connect('mongodb://node:noder@novus.modulusmongo.net:27017/Iganiq8o'); // MEAN machine db (scotch.io) | |
// Routers | |
var adminRouter = express.Router(); // for /admin | |
var apiRouter = express.Router(); // for APIs | |
// API ROUTES --------------------------------- | |
// accessed at GET http://localhost:8615/api | |
// middleware to use for all requests | |
apiRouter.use(function(req, res, next) { | |
console.log('Somebody just came to our app!'); | |
// we'll add more to the middleware in Chapter 10 | |
// this is where we will authenticate users | |
next(); | |
}); | |
apiRouter.get('/', function(req, res) { | |
res.json({ message: 'hooray! welcome to our api!' }); | |
}); | |
// api/users | |
apiRouter.route('/users') | |
// create a user (accessed at POST http://localhost:8615/api/users) | |
.post(function(req, res) { | |
// create a new instance of the User model | |
var user = new User(); | |
// set the users information (comes from the request) | |
user.name = req.body.name; | |
user.username = req.body.username; | |
user.password = req.body.password; | |
// save the user and check for errors | |
user.save(function(err) { | |
if (err) { | |
// duplicate entry | |
if (err.code == 11000) | |
return res.json({ success: false, message: 'A user with that username already exists. '}); | |
else | |
return res.send(err); | |
} | |
// return a message | |
res.json({ message: 'User created!' }); | |
}); | |
}) | |
// get all users (access at GET http://localhost:8615/api/users) | |
.get(function(req, res) { | |
User.find(function(err, users) { | |
if (err) return res.send(err); | |
// return the users | |
res.json(users); | |
}) | |
}); | |
// api/users/:user_id | |
apiRouter.route('/users/:user_id') | |
// get the user with that id | |
// (accessed at GET http://localhost:8615/api/users/:user_id) | |
.get(function(req, res) { | |
User.findById(req.params.user_id, function(err, user) { | |
if (err) return res.send(err); | |
// return that user | |
res.json(user); | |
}) | |
// update the user with this id | |
.put(function(req, res) { | |
// use our user model to find the user we want | |
User.findById(req.params.user_id, function (err, user) { | |
if (err) return res.send(err); | |
// update the users info only if its new | |
if (req.body.name) user.name = req.body.name; | |
if (req.body.username) user.username = req.body.username; | |
if (req.body.password) user.password = req.body.password; | |
// save the user | |
user.save(function(err) { | |
if (err) return res.send(err); | |
// return a message | |
res.json({ message: 'User updated!' }); | |
}); | |
}) | |
}) | |
// delete the user with this id | |
.delete(function(req, res) { | |
User.remove({ | |
_id: req.params.user_id | |
}, function(err, user) { | |
if (err) return res.send(err); | |
res.json({ message: 'Successfully deleted' }); | |
}); | |
}); | |
}); | |
// PUBLIC ROUTES ------------------------------ | |
app.get('/', function (req, res) { | |
res.sendFile(__dirname + '/index.html'); | |
}); | |
app.route('/login') | |
// show the form | |
.get(function (req, res) { | |
res.send('this is the login form'); | |
}) | |
// process the form | |
.post(function (req, res) { | |
console.log('processing'); | |
res.send('processing the login form'); | |
}); | |
// ADMIN ROUTES ------------------------------- | |
// route middleware that happens on every request | |
adminRouter.use(function(req, res, next) { | |
console.log(req.method, req.url); | |
next(); | |
}); | |
adminRouter.get('/', function(req, res) { | |
res.send('I am the Admin page!'); | |
}); | |
// users page /admin/users | |
adminRouter.get('/users', function(req, res) { | |
res.send('I show all the users!'); | |
}); | |
// middleware to validate :name | |
adminRouter.param('name', function(req, res, next, name) { | |
// do validation on name | |
// blah blah validation | |
// log something | |
console.log('doing name validations on ' + name); | |
// once validation is done save the new item in the req | |
req.name = name; | |
next(); | |
}); | |
// route with parameters /admin/users/:name | |
adminRouter.get('/users/:name', function(req, res) { | |
res.send('hello '+req.params.name + '!'); | |
}); | |
// users page /admin/posts | |
adminRouter.get('/posts', function(req, res) { | |
res.send('I show all the posts!'); | |
}); | |
// REGISTER OUR ROUTES ------------------------------- | |
app.use('/api', apiRouter); | |
app.use('/admin', adminRouter); | |
// START THE SERVER | |
// ============================================================================= | |
app.listen(port); | |
console.log('Magic happens on port ' + port + '!'); | |
/* raw Node */ | |
// // get the http and filesystem modules | |
// var http = require('http') | |
// fs = require('fs'); | |
// // create our server using the http module | |
// http.createServer(function(req, res) { | |
// // write to our server. set configuration for the response | |
// res.writeHead(200, { | |
// 'Content-Type': 'text/html', | |
// 'Access-Control-Allow-Origin' : '*' | |
// }); | |
// // grab the index.html file using fs | |
// var readStream = fs.createReadStream(__dirname + '/index.html'); | |
// // send the index.html file to our user | |
// readStream.pipe(res); | |
// }).listen(1337); | |
// // tell ourselves what's happening | |
// console.log('Visit me at http://localhost:1337'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment