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
5 changes: 5 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
**/node_modules/*
**/vendor/*
**/*.min.js
**/coverage/*
**/build/*
21 changes: 21 additions & 0 deletions .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"
}
137 changes: 137 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# Created by https://www.gitignore.io/api/osx,vim,node,macos,windows

### 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

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.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

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

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

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# 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

# dotenv environment variables file
.env


### OSX ###

# Icon must end with two \r

# Thumbnails

# Files that might appear in the root of a volume

# Directories potentially created on remote AFP share

### Vim ###
# swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]
# session
Session.vim
# temporary
.netrwhist
*~
# auto-generated tag files
tags

### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Folder config file
Desktop.ini

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

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

# Windows shortcuts
*.lnk

# End of https://www.gitignore.io/api/osx,vim,node,macos,windows
Contact GitHub API Training Shop Blog About
56 changes: 6 additions & 50 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,53 +1,9 @@
![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API
======
# Baked Goods API

## Submission Instructions
* fork this repository & create a new branch for your work
* write all of your code in a directory named `lab-` + `<your name>` **e.g.** `lab-susan`
* push to your repository
* submit a pull request to this repository
* submit a link to your PR in canvas
* write a question and observation on canvas
This REST API uses express to route incoming requests.

## Learning Objectives
* students will be able to create a single resource API using the express framework
* students will be able to leverage 3rd party helper modules for debugging, logging, and handling errors
# Endpoints

## Requirements

#### Configuration
* `package.json`
* `.eslintrc`
* `.gitignore`
* `README.md`
* your `README.md` should include detailed instructions on how to use your API

#### Feature Tasks
* create an HTTP server using `express`
* create a object constructor that creates a _simple resource_ with at least 3 properties
* it can **not** have the same properties as the in-class sample code (other than the `id`)
* a unique `id` property should be included *(node-uuid)*
* include two additional properties of your choice
* use the JSON parser included with the `body-parser` module as a middleware component to parse the request body on `POST` and `PUT` routes
* use the npm `debug` module to log the methods in your application
* create an `npm` script to automate the `debug` process and start the server
* persist your API data using the storage module and file system persistence

#### Server Endpoints
* **`/api/simple-resource-name`**
* `POST` request
* pass data as stringifed JSON in the body of a **POST** request to create a new resource
* `GET` request
* pass `?id=<uuid>` as a query string parameter to retrieve a specific resource (as JSON)
* `DELETE` request
* pass `?id=<uuid>` in the query string to **DELETE** a specific resource
* this should return a 204 status code with no content in the body

#### Tests
* write a test to ensure that your api returns a status code of 404 for routes that have not been registered
* write tests to ensure the `/api/simple-resource-name` endpoint responds as described for each condition below:
* `GET`: test 404, it should respond with 'not found' for valid requests made with an id that was not found
* `GET`: test 400, it should respond with 'bad request' if no id was provided in the request
* `GET`: test 200, it should contain a response body for a request made with a valid id
* `POST`: test 400, it should respond with 'bad request' if no request body was provided or the body was invalid
* `POST`: test 200, it should respond with the body content for a post request with a valid body
**GET** : '/'
**POST** : '/api/bake?id=<bakedGood_id>
**DELETE** : '/api/bake?id=<bakedGood_id>
1 change: 1 addition & 0 deletions data/bake/b78e48ca-3201-4aeb-8f05-158a6bfab915.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"b78e48ca-3201-4aeb-8f05-158a6bfab915","bakedGood":"muffin","description":"naked cupcake","calories":255}
49 changes: 49 additions & 0 deletions lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict';

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'), { suffix: 'Prom' });
const createError = require('http-errors');
const debug = require('debug')('bake:storage');

module.exports = exports = {};

exports.createItem = function(schemaName, item) {
debug('create item');

if (!schemaName) return Promise.reject(createError(400, 'expected schema name'));
if (!item) return Promise.reject(createError(400, 'expected item'));

let json = JSON.stringify(item);
return fs.writeFileProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json)
.then( () => item)
.catch( () => Promise.reject(createError(400, 'unable to write file')));
};

exports.fetchItem = function(schemaName, id) {
debug('fetch item');

if (!schemaName) return Promise.reject(createError(400, 'expected schema name'));
if (!id) return Promise.reject(createError(400, 'expected id'));

return fs.readFileProm(`${__dirname}/../data/${schemaName}/${id}.json`)
.then( data => {
try {
let item = JSON.parse(data.toString());
return item;
} catch (err) {
return Promise.reject(createError(404, 'expected SOMETHING'));
}
})
.catch( () => Promise.reject(createError(404, 'no file found')));
};

exports.deleteItem = function(schemaName, id) {
debug('delete item');

if (!schemaName) return Promise.reject(createError(400, 'expected schema name'));
if (!id) return Promise.reject(createError(400, 'expected id'));

return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`)
.then( () => console.log(`${id} deleted`))
.catch( err => Promise.reject(err));
};
41 changes: 41 additions & 0 deletions model/bake.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

const uuidv4 = require('uuid/v4');
const createError = require('http-errors');
const debug = require('debug')('bake:bake');
const storage = require('../lib/storage.js');

const Bake = module.exports = function(bakedGood, description, calories) {
if (!bakedGood) throw createError(400, 'expected baked good');
if (!description) throw createError(400, 'expected description');
if (!calories) throw createError(400, 'expected expected calories');

this.id = uuidv4();
this.bakedGood = bakedGood;
this.description = description;
this.calories = calories;
};

Bake.createBakedGood = function(_bake) {
debug('createBakedGood');

try {
let bake = new Bake(_bake.bakedGood, _bake.description, _bake.calories);
return storage.createItem('bake', bake);
} catch (err) {
return Promise.reject(err);
}
};

Bake.fetchBakedGood = function(id) {
debug('fetchBakedGood');

return storage.fetchItem('bake', id);
};

Bake.deleteBakedGood = function(id) {
debug('deleteBakedGood');

return storage.deleteItem('bake', id);
};

38 changes: 38 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "11-express-api",
"version": "1.0.0",
"description": "![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API ======",
"main": "server.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "mocha",
"start": "DEBUG='bake*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ohjonah/11-express-api.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/ohjonah/11-express-api/issues"
},
"homepage": "https://github.com/ohjonah/11-express-api#readme",
"devDependencies": {
"bluebird": "^3.5.0",
"body-parser": "^1.17.2",
"chai": "^4.1.0",
"debug": "^2.6.8",
"http-errors": "^1.6.1",
"mocha": "^3.5.0",
"morgan": "^1.8.2",
"superagent": "^3.5.2",
"uuid": "^3.1.0"
},
"dependencies": {
"express": "^4.15.3"
}
}
Loading