Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
1423a68
set up directory structure
kcirekcom Dec 15, 2016
25b672e
set up the port for the server
kcirekcom Dec 15, 2016
03c9b0e
created object constructor of simple resource
kcirekcom Dec 15, 2016
9fba3d0
built out functionality for body parser module
kcirekcom Dec 15, 2016
0eadbc8
built out functionality for url parser module
kcirekcom Dec 15, 2016
7f38106
created router constuctor
kcirekcom Dec 15, 2016
eed2852
storage module created
kcirekcom Dec 15, 2016
c2090bc
added consts in server.js
kcirekcom Dec 15, 2016
99c64ea
created route.post in server.js
kcirekcom Dec 15, 2016
9daafeb
created router.get in server.js, api requests are working
kcirekcom Dec 15, 2016
3fb4122
delete route seems to be working
kcirekcom Dec 15, 2016
0cc55a2
test for delete route passes
kcirekcom Dec 15, 2016
12a97e8
modified delete route
kcirekcom Dec 15, 2016
4f83b90
adding README.md
kcirekcom Dec 15, 2016
0c16159
updated README.md
kcirekcom Dec 15, 2016
5f7dd7b
400 and 404 response tests are passing
kcirekcom Dec 16, 2016
cb20c1d
refactored server.js and exported pin-route module to server
kcirekcom Dec 16, 2016
4fe6abb
response helpers created, pin-route refactored with response helpers
kcirekcom Dec 16, 2016
5fef952
deleteItem route is working, tests passing
kcirekcom Dec 16, 2016
25f94cf
updated README
kcirekcom Dec 16, 2016
e02b0f1
refactored response statuses in router.js
kcirekcom Dec 16, 2016
4faa28d
refactored no content response in pin-route.js
kcirekcom Dec 16, 2016
ba5545e
changed ports in test to 3000
kcirekcom Dec 16, 2016
42a4494
updated a test
kcirekcom Dec 16, 2016
e5f08da
updated ports in README
kcirekcom Dec 16, 2016
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
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Vanilla REST API

## Overview

This is a basic API app that allows a developer to POST, GET and DELETE data from an API. A developer should be able to see 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.

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

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

### DELETE requests
* **i.e.** 204 No Content request: `http DELETE localhost:3000/api/pin?id=69df11c0-c2fd-11e6-8512-d5d43d0553c1`
* You must pass in a query string equal to the unique id of the pin you want to delete.
* **i.e.** 400 BAD request: `http localhost:3000/api/pin`
* You should receive a response with a 'bad request' message.

GET, POST and DELETE request commands should be run in the second terminal pane. JSON files should be posted and deleted from the `/data/pin` folder depending on your terminal commands.
1 change: 1 addition & 0 deletions data/pin/22f30480-c35f-11e6-b975-93db3f47cc6c.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"22f30480-c35f-11e6-b975-93db3f47cc6c","title":"test title","skill":"test skill"}
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']);
27 changes: 27 additions & 0 deletions lib/parse-json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict';

module.exports = function(req) {
return new Promise((resolve, reject) => {
if (req.method === 'POST' || req.method === 'PUT') {
var body = '';
req.on('data', data => {
body += data.toString();
});
req.on('end', () => {
try {
req.body = JSON.parse(body);
resolve(req);
} catch (err) {
console.error(err);
reject(err);
}
});
req.on('error', err => {
console.error(err);
reject(err);
});
return;
}
resolve();
});
};
10 changes: 10 additions & 0 deletions lib/parse-url.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

const parseUrl = require('url').parse;
const parseQuery = require('querystring').parse;

module.exports = function(req) {
req.url = parseUrl(req.url);
req.url.query = parseQuery(req.url.query);
return Promise.resolve(req);
};
24 changes: 24 additions & 0 deletions lib/response.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';

module.exports = exports = {};

exports.sendJSON = function(res, status, data) {
res.writeHead(status, {
'Content-Type': 'application/json'
});
res.write(JSON.stringify(data));
res.end();
};

exports.sendText = function(res, status, msg) {
res.writeHead(status, {
'Content-Type': 'text/plain'
});
res.write(msg);
res.end();
};

exports.sendNoContent = function(res, status) {
res.writeHead(status);
res.end();
};
48 changes: 48 additions & 0 deletions lib/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
'use strict';

const parseUrl = require('./parse-url.js');
const parseJSON = require('./parse-json.js');
const response = require('../lib/response.js');

const Router = module.exports = function() {
this.routes = {
GET: {},
POST: {},
PUT: {},
DELETE: {}
};
};

Router.prototype.get = function(endpoint, callback) {
this.routes.GET[endpoint] = callback;
};
Router.prototype.post = function(endpoint, callback) {
this.routes.POST[endpoint] = callback;
};
Router.prototype.put = function(endpoint, callback) {
this.routes.PUT[endpoint] = callback;
};
Router.prototype.delete = function(endpoint, callback) {
this.routes.DELETE[endpoint] = callback;
};

Router.prototype.route = function() {
return (req, res) => {
Promise.all([
parseUrl(req),
parseJSON(req)
])
.then(() => {
if (typeof this.routes[req.method][req.url.pathname] === 'function') {
this.routes[req.method][req.url.pathname](req, res);
return;
}
console.error('route not found');
response.sendText(res, 404, 'route not found');
})
.catch(err => {
console.error(err);
response.sendText(res, 400, 'bad request');
});
};
};
35 changes: 35 additions & 0 deletions lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'), {suffix: 'Prom'});

module.exports = exports = {};

exports.createItem = function(schemaName, item) {
if (!schemaName) return Promise.reject(new Error('expected schema name'));
if (!item) return Promise.reject(new Error('expected item'));

let json = JSON.stringify(item);
return fs.writeFileProm(`${__dirname}/../data/${schemaName}/${item.id}.json`, json)
.then(() => item)
.catch(err => Promise.reject(err));
};

exports.fetchItem = function(schemaName, id) {
if (!schemaName) return Promise.reject(new Error('expected schema name'));
if (!id) return Promise.reject(new Error('expected id'));

return fs.readFileProm(`${__dirname}/../data/${schemaName}/${id}.json`)
.then(data => {
let item = JSON.parse(data.toString());
return item;
})
.catch(err => Promise.reject(err));
};

exports.deleteItem = function(schemaName, id) {
if (!schemaName) return Promise.reject(new Error('expected schema name'));
if (!id) return Promise.reject(new Error('expected id'));

return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`);
};
12 changes: 12 additions & 0 deletions model/pin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

const uuid = require('node-uuid');

module.exports = function(title, skill) {
if (!title) throw new Error('expected title');
if (!skill) throw new Error('expected skill');

this.id = uuid.v1();
this.title = title;
this.skill = skill;
};
36 changes: 36 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "08-vanilla_rest_api",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/kcirekcom/08-vanilla_rest_api.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/kcirekcom/08-vanilla_rest_api/issues"
},
"homepage": "https://github.com/kcirekcom/08-vanilla_rest_api#readme",
"dependencies": {
"bluebird": "^3.4.6",
"node-uuid": "^1.4.7"
},
"devDependencies": {
"chai": "^3.5.0",
"gulp": "^3.9.1",
"gulp-eslint": "^3.0.1",
"gulp-mocha": "^3.0.1",
"mocha": "^3.2.0",
"superagent": "^3.3.0"
}
}
Loading