Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions lab-steven/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"rules": {
"no-console": "off",
"indent": [ "error", 2 ],
"quotes": [ "error", "single" ],
"semi": ["error", "always"],
"linebreak-style": [ "error", "unix" ]
},
"env": {
"es6": true,
"node": true,
"mocha": true,
"jasmine": true
},
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true
},
"extends": "eslint:recommended"
}
113 changes: 113 additions & 0 deletions lab-steven/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@

# Created by https://www.gitignore.io/api/windows,macos,linux,node

### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk


### macOS ###
*.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk


### Linux ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*


### Node ###
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity
41 changes: 41 additions & 0 deletions lab-steven/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#Single Resource MongoDB API
###Steven Bateman's Lab 13 for 401 JS

###Overview
This is an app that will allow you to practice POST, PUT, GET, and DELETE requests using HTTPIE against a database created with MongoDB that tracks a single resource, in the form of students with a name and age field.

###Installation
####Dependencies
You will need to install HTTPIE and MongoDB prior to getting this app working. For HTTPIE:

* On Macs: `brew install httpie`
* On Linux: `sudo apt install httpie`

For MongoDB, please visit [The Little MongoDB Book](http://openmymind.net/mongodb.pdf) and find instructions there.

####Main app
Once you have installed HTTPIE and MongoDB, clone down this repository, then navigate to the `lab-steven` directory and run `npm i`.

###Usage
This app makes use of Mongoose, which will require a running process of MongoDB in the background. Within your terminal, type `mongod` to begin a process of a Mongo database. Then in another tab/shell, run `npm start` for debug mode or `node server.js` to just run the basic server.

###POST Requests
To make a POST request, you will need to use HTTPIE to connect to `localhost:<port#>/api/student` and pass in a header object with name and age fields.

* Ex: `http POST localhost:8080/api/student name="Tester" age=45`

###GET Requests
To make a GET request, connect to the api/student path and additionally pass in the ID of the student you want to look at. If you do not pass in an ID, you will get back an array of all possible IDs.

* Ex: `http localhost:8080/api/student` (Will return all available student IDs)
* Ex: `http localhost:8080/api/student/3838u8ad98f9` (Will return back the student with that ID)

###PUT Requests
To update a student in the database, do the same thing you would to GET an ID, but also include a header object with the fields you wish to update. This app will not currently upsert any students, so you cannot POST a student by doing a PUT request for an ID that doesn't exist.

* Ex: `http PUT localhost:8080/api/student/3838u8ad98f9 name="Weasel" age=9999`

###DELETE Requests
To delete a student from the database, simply perform the same task as a GET request.

* Ex: `http DELETE localhost:8080/api/student/3838u8ad98f9`
14 changes: 14 additions & 0 deletions lab-steven/gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

const gulp = require('gulp');
const mocha = require('gulp-mocha');

gulp.task('test', function() {
gulp.src('./test/*-test.js', {read: false}).pipe(mocha({reporter: 'spec'}));
});

gulp.task('dev', function() {
gulp.watch(['**/*.js', '!node_modules/**'], ['test']);
});

gulp.task('default', ['dev']);
12 changes: 12 additions & 0 deletions lab-steven/model/student.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const studentSchema = Schema({
name: {type: String, required: true},
age: {type: Number, required: true},
timestamp: {type: Date, required: true}
});

module.exports = mongoose.model('student', studentSchema);
32 changes: 32 additions & 0 deletions lab-steven/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "mongo-demo",
"version": "1.0.0",
"description": "",
"main": "server.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "DEBUG='student*' mocha",
"start": "DEBUG='student*' node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bluebird": "^3.4.6",
"body-parser": "^1.15.2",
"cors": "^2.8.1",
"debug": "^2.5.1",
"express": "^4.14.0",
"mongoose": "^4.7.4",
"morgan": "^1.7.0"
},
"devDependencies": {
"chai": "^3.5.0",
"gulp": "^3.9.1",
"gulp-mocha": "^3.0.1",
"mocha": "^3.2.0",
"superagent": "^3.3.1"
}
}
53 changes: 53 additions & 0 deletions lab-steven/route/student-route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

const Router = require('express').Router;
const parseJSON = require('body-parser').json();
const debug = require('debug')('student:student-router');
const Student = require('../model/student.js');
const studentRouter = module.exports = new Router();

studentRouter.post('/api/student', parseJSON, (request, response, next) => {
debug('Student router POST: /api/student');

request.body.timestamp = new Date();
new Student(request.body).save()
.then(student => response.json(student))
.catch(next);
});

studentRouter.put('/api/student/:id', parseJSON, (request, response, next) => {
debug('Student router PUT: /api/student/:id');
if (Object.keys(request.body).length < 1) {
response.status(400).send();
throw new Error('No content passed in.');
}

request.body.timestamp = new Date();
Student.findByIdAndUpdate(request.params.id, request.body, {new: true})
.then(student => response.json(student))
.catch(next);
});

studentRouter.get('/api/student/:id', (request, response, next) => {
debug('Student router GET: /api/student/:id');

Student.findById(request.params.id)
.then(student => response.json(student))
.catch(next);
});

studentRouter.get('/api/student', (request, response, next) => {
debug('Student router GET: /api/student');

Student.find()
.then(arrayOfStudents => response.json(arrayOfStudents.map(ele => ele._id)))
.catch(next);
});

studentRouter.delete('/api/student/:id', (request, response, next) => {
debug('Student router DELETE: /api/student/:id');

Student.findByIdAndRemove(request.params.id)
.then(() => response.status(204).send())
.catch(next);
});
23 changes: 23 additions & 0 deletions lab-steven/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';

const express = require('express');
const debug = require('debug')('student:server');
const cors = require('cors');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const studentRouter = require('./route/student-route.js');
const morgan = require('morgan');
const app = express();
const PORT = process.env.PORT || 8080;
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost/listdev';

app.use(morgan('dev'));
app.use(cors());
app.use(studentRouter);

mongoose.Promise = Promise;
mongoose.connect(MONGODB_URI);

app.listen(PORT, () => {
debug(`Server started on port ${PORT}.`);
});
Loading