Skip to content

Instantly share code, notes, and snippets.

@HavishNetla
Last active July 26, 2018 21:15
Show Gist options
  • Save HavishNetla/1b5320d4a169d5190111485f863924e9 to your computer and use it in GitHub Desktop.
Save HavishNetla/1b5320d4a169d5190111485f863924e9 to your computer and use it in GitHub Desktop.
// BASE SETUP
// =============================================================================
// call the packages we need
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const morgan = require('morgan')
// Some stuff someone on reactiflux told me to do
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
res.header(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, Content-Length, X-Requested-With',
)
// Intercepts OPTIONS method
if (req.method === 'OPTIONS') {
// Respond with 200
res.send(200)
} else {
// Move on
next()
}
})
// Configure app
app.use(morgan('dev')) // Log requests to the console
// configure body parser
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
const port = process.env.PORT || 8080 // Set our port
// DATABASE SETUP
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/apiTest') // Connect to our database
// Handle the connection event
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', () => {
console.log('DB connection alive')
})
// Food models lives here
const Food = require('./app/models/food')
// ROUTES FOR OUR API
// =============================================================================
// create our router
const router = express.Router()
// Middleware to use for all requests
router.use((req, res, next) => {
// Do logging
console.log('Something is happening.')
next()
})
// Test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', (req, res) => {
res.json({ message: 'hooray! welcome to our api!' })
})
// On routes that end in /foods
// ----------------------------------------------------
router
.route('/foods')
// Create a food (accessed at POST http://localhost:8080/foods)
.post((req, res) => {
const food = new Food() // Create a new instance of the food model
// Set the foods name (comes from the request)
food.name = req.body.name
food.food = req.body.food
food.number = req.body.number
food.address1 = req.body.address1
food.address2 = req.body.address2
food.city = req.body.city
food.state = req.body.state
food.zip = req.body.zip
food.save(err => {
if (err) res.send(err)
res.json({ message: 'food created!' })
})
})
// Get all the foods (accessed at GET http://localhost:8080/api/foods)
.get((req, res) => {
Food.find((err, foods) => {
if (err) res.send(err)
res.json(foods)
})
})
// On routes that end in /foods/:food_id
// ----------------------------------------------------
router
.route('/foods/:food_id')
// Get the food with that id
.get((req, res) => {
Food.findById(req.params.food_id, (err, food) => {
if (err) res.send(err)
res.json(food)
})
})
// Update the food with this id
.put((req, res) => {
Food.findById(req.params.food_id, (err, food) => {
if (err) res.send(err)
// Set the foods name (comes from the request)
food.userName = req.body.name
food.userFood = req.body.food
food.userNumber = req.body.number
food.userStreetAddress1 = req.body.address1
food.userStreetAddress2 = req.body.address2
food.userCity = req.body.city
food.userState = req.body.state
food.userZip = req.body.zip
food.save(err => {
if (err) res.send(err)
res.json({ message: 'Food updated!' })
})
})
})
// Delete the food with this id
.delete((req, res) => {
Food.remove(
{
_id: req.params.food_id,
},
(err, food) => {
if (err) res.send(err)
res.json({ message: 'Successfully deleted' })
},
)
})
// REGISTER OUR ROUTES -------------------------------
app.use('/api', router)
// START THE SERVER
// =============================================================================
app.listen(port)
console.log(`Magic happens on port ${port}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment