Skip to content

Instantly share code, notes, and snippets.

@eshaben
Created July 24, 2017 02:52
Show Gist options
  • Save eshaben/41ba5f9a346f89905b1deb4564ea4162 to your computer and use it in GitHub Desktop.
Save eshaben/41ba5f9a346f89905b1deb4564ea4162 to your computer and use it in GitHub Desktop.

CRUD!

Create (post route), Read (get route), Update (put route), Delete (delete route)

Let's create a CRUD requests!

The top of our file will look like this:

var express = require (‘express’)
var knex = require(‘../db/knex’)
var router = express.Router()
  1. Create a GET request to get all exercises
router.get(‘/‘, function (req, res) {
	knex(‘exercise’)
	.then(exercises => {
		res.json(exercises)
	});
});
  1. Create a GET request to get an exercise by id number
router.get(‘/:id’, (req, res) => {
 	let id= req.params.id;
	knex(‘exercise’)
	 .where(‘id’, id).first()
	 .then(exercise => {
	 	res.json(exercise)
	});	
});
  1. Create a POST request to add the request body to our database
router.post(‘/‘, (req, res) => {
	let post = req.body;
	knex(‘exercise’).insert(post)
		.returning(‘*’)
		.then(exercise => {
			res.json(exercise)
	});
});
  1. Create a PUT request to update a specific entry in our database
router.put(‘/:id’, (req, res) => {
	let id = req.params.id;
	let edit = req.body;
	knex(‘exercise’).where(‘id’, id)
		.update(edit)
		.returning(‘*’)
		.then(edited => {
			res.json(edited)
	})
});
  1. Create a DELETE request to delete a specific entry in our database
router.delete(‘/:id’, (req, res) => {
	let id = req.params.id;
	knex(‘exercise’)
		.where(‘id’, id).del()
		.then(deleted => {
			res.json({
				“message”: ‘Record Deleted!!’,
				“deleted”: deleted
		})
	});
})
  1. Our file will end with module:exports = router; because this is essentially a seperarate file for our routes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment