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 .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 .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@

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

### OSX ###
*.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*


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


### 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
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Single-Resource Express REST API

## Overview

This is a basic Express API app that allows a developer to POST, PUT and GET data from an API. A developer will be able to view the appropriate response statuses when interacting with the API.

## How do I use this app?

* Clone this repo and run the command `npm i` in your terminal to install all of the dependencies.

* You will also need to run the command `brew install httpie`. For this app, the requests used in the terminal are formatted via HTTPie CLI.

* Open 2 panes in your terminal to get started. You should see the type of requests and response status codes in both terminal panes.

* Be sure that you are in the root of the repo directory before attempting to initiate the port to the server. To do this, run `node server.js` in the first terminal pane.
* `server running:` followed by your PORT number should be logged in the terminal

### POST requests
* **i.e.** 200 OK request: `http POST localhost:3000/api/pin title="sample title" skill="sample skill"`
* You should receive a response with the content of the appropriate pin you just posted.
* **i.e.** 400 BAD request: `http POST localhost:3000/api/pin` (no title and skill is attached to POST request)
* You should receive a response with a 'Bad Request' message.

### PUT requests
* **i.e.** 200 OK request: `http PUT localhost:3000/api/pin?id=292873e0-c7af-11e6-8037-af3dde2fd6df title="different title" skill="different skill"`
* You must pass in a query string equal to the unique id of the pin you want to delete.
* You can change the title and skill content by passing them in after the unique pin id.
* **i.e.** 400 BAD request: `http localhost:3000/api/pin`
* You should receive a response with a 'Bad Request' message.

### GET requests
* **i.e.** 200 OK request: `http localhost:3000/api/pin?id=17b389b0-c2ff-11e6-9794-69f9c8e1c4f5`
* You must pass in a query string equal to the unique id of the pin you want to retrieve.
* You should receive a response with the content of the appropriate pin.
* **i.e.** 400 BAD request: `http localhost:3000/api/pin`
* You should receive a response with a 'Bad Request' message.


POST, PUT and GET request commands should be run in the second terminal pane. JSON files will be posted to the file system, specifically the `/data/pin` folder depending on your terminal commands.
1 change: 1 addition & 0 deletions data/pin/292873e0-c7af-11e6-8037-af3dde2fd6df.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"292873e0-c7af-11e6-8037-af3dde2fd6df","title":"title of new","skill":"skill of new"}
23 changes: 23 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';

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

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

gulp.task('lint', function(){
return gulp.src(['**/*.js','!node_modules/**'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});

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

gulp.task('default', ['dev']);
7 changes: 7 additions & 0 deletions lib/cors-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

module.exports = function(req, res, next) {
res.append('Access-Control-Allow-Origin', '*');
res.append('Access-Control-Allow-Headers', '*');
next();
};
21 changes: 21 additions & 0 deletions lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

const createError = require('http-errors');
const debug = require('debug')('pin:error-middleware');

module.exports = function(err, req, res, next) {
console.error(err.message);

if (err.status) {
debug('user error');

res.status(err.status).send(err.name);
next();
return;
}

debug('server error');
err = createError(500, err.message);
res.status(err.status).send(err.name);
next();
};
50 changes: 50 additions & 0 deletions lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict';

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

module.exports = exports = {};

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

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(err => Promise.reject(createError(500, err.message)));
};

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

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 => {
let item = JSON.parse(data.toString());
return item;
})
.catch( err => Promise.reject(createError(404, err.message)));
};

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

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`)
.catch( err => Promise.reject(createError(404, err.message)));
};

exports.availIDs = function(schemaName) {
return fs.readdirProm(`${__dirname}/../data/${schemaName}`)
.then( files => files.map( name => name.split('.json')[0]))
.catch( err => Promise.reject(createError(404, err.message)));
};
57 changes: 57 additions & 0 deletions model/pin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict';

const uuid = require('node-uuid');
const createError = require('http-errors');
const debug = require('debug')('pin:pin');
const storage = require('../lib/storage.js');

const Pin = module.exports = function(title, skill) {
debug('pin constructor');

if (!title) throw createError(400, 'expected title');
if (!skill) throw createError(400, 'expected skill');

this.id = uuid.v1();
this.title = title;
this.skill = skill;
};

Pin.createPin = function(_pin) {
debug('createPin');

try {
let pin = new Pin(_pin.title, _pin.skill);
return storage.createItem('pin', pin);
} catch (err) {
return Promise.reject(createError(400, err.message));
}
};

Pin.fetchPin = function(id) {
debug('fetchPin');
return storage.fetchItem('pin', id);
};

Pin.updatePin = function(id, _pin) {
debug('updatePin');

return storage.fetchItem('pin', id)
.catch(err => Promise.reject(createError(404, err.message)))
.then(pin => {
for (var prop in pin) {
if (prop === 'id') continue;
if (_pin[prop]) pin[prop] = _pin[prop];
}
return storage.createItem('pin', pin);
});
};

Pin.deletePin = function(id) {
debug('deletePin');
return storage.deleteItem('pin', id);
};

Pin.fetchIDs = function() {
debug('fetchIDs');
return storage.availIDs('pin');
};
37 changes: 37 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "12-express_middleware",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "DEBUG='note*' node server.js",
"test": "DEBUG='note*' mocha"
},
"repository": {
"type": "git",
"url": "git+https://github.com/kcirekcom/12-express_middleware.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/kcirekcom/12-express_middleware/issues"
},
"homepage": "https://github.com/kcirekcom/12-express_middleware#readme",
"dependencies": {
"bluebird": "^3.4.6",
"body-parser": "^1.15.2",
"debug": "^2.4.5",
"express": "^4.14.0",
"http-errors": "^1.5.1",
"morgan": "^1.7.0",
"node-uuid": "^1.4.7"
},
"devDependencies": {
"chai": "^3.5.0",
"gulp-eslint": "^3.0.1",
"gulp-mocha": "^3.0.1",
"mocha": "^3.2.0",
"superagent": "^3.3.1"
}
}
Loading