Created
March 5, 2017 15:01
-
-
Save aamnah/80d388ae758643f05b9843a1fa0798c5 to your computer and use it in GitHub Desktop.
Basic API using Nodejs + Express + MongoDB (less than 100 lines of code, adds + finds vehicles)
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
/* | |
path: server.js | |
*/ | |
// Require shit | |
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const mongoose = require('mongoose'); | |
// Let's import our Vehicle model | |
let Vehicle = require('./app/models/vehicle') | |
// Initiate an express app | |
const app = express(); | |
// Configure app for bodyParser() | |
// this lets us get data from the body of POST | |
app.use(bodyParser.urlencoded({ extended: true })) // URL encoded data | |
app.use(bodyParser.json()) // JSON | |
// Set up port for server to listen on | |
const PORT = process.env.PORT || 3000; // if env variable is set for port, use it. else, use 3000 | |
// connect to DB | |
mongoose.connect('mongodb://localhost:27017/codealong') // 27017 is the default MongoDB port, 'codealong' will be the DB name | |
// API routes | |
const router = express.Router(); // we're gonna use Express router for routing in our API | |
// Routes will all be prefixed with /api/ | |
app.use('/api', router) | |
// MIDDLEWARE | |
// Middleware can be very useful for doing validations. | |
// We can log things from here or stop the request from continuing | |
// in the event that the request is not safe | |
// middleware will step in before a request gets to the route and run some process, whatever you need, | |
// before it moves on | |
// middleware to use for all requests | |
router.use(function(req, res, next) { | |
console.log('Middleware meddled. Something is happening here..') | |
next(); // we always need to call this next() so the request could move on, otherwise it wouldn't complete | |
}); | |
// Test route | |
router.get('/', function(req, res) { | |
res.json({ message: 'Welcome to our API' }) | |
}) | |
// ENDPOINTS | |
router.route('/vehicles') | |
.post(function(req, res) { // create a new instance of a car based on our data (Vehicle) model | |
let vehicle = new Vehicle(); | |
vehicle.make = req.body.make; | |
vehicle.model = req.body.model; | |
vehicle.color = req.body.color | |
vehicle.save(function(err) { | |
if (err) { | |
res.send(err) // if error, send error in response | |
} | |
res.json({ message: 'Vehicle was successfully manufactured' }); // if not error, send a success msg | |
}); | |
}) | |
.get(function(req, res) { | |
Vehicle.find(function(err, vehicles) { | |
if (err) { | |
res.send(err) | |
} | |
res.json(vehicles); // if no err, send all the vehicles back as JSON | |
}) // return all vehicles | |
}); | |
router.route('/vehicle/:vehicle_id') | |
.get(function(req, res) { | |
Vehicle.findById(req.params.vehicle_id, function(err, vehicle) { | |
if (err) { | |
res.send(err) | |
} | |
res.json(vehicle) | |
}) | |
}) | |
router.route('/vehicles/make/:make') | |
.get(function(req, res) { | |
Vehicle.find({make: req.params.make}, function(err, vehicle) { | |
if (err) { | |
res.send(err) | |
} | |
res.json(vehicle) | |
}) | |
}) | |
router.route('/vehicles/color/:color') | |
.get(function(req,res) { | |
Vehicle.find({color:req.params.color}, function(err, vehicle) { | |
if (err) { | |
res.send(err) | |
} | |
res.json(vehicle) | |
}) | |
}) | |
// Fire up server | |
app.listen(PORT) | |
// Print friendly msg to console | |
console.info(`Connected. Server listening on port: ${PORT}`) | |
// You should have MongoDB running in order to serve this API | |
// Start your app with nodemon, it 'watches' for changes, to run: nodemon server.js |
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
/* | |
path: app/models/vehicle.js | |
*/ | |
const mongoose = require('mongoose') | |
let Schema = mongoose.Schema; | |
// Let's make a model for a vehicle | |
const VehicleSchema = new Schema({ | |
// Let's add some props | |
make: String, | |
model: String, | |
color: String | |
}); | |
// export so we can pull this from some other location | |
module.exports = mongoose.model('Vehicle', VehicleSchema) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment