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

## General description

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 see how you, as the developer, can interact with this server.

* 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:8000/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:8000/api/pin` (no title and/or 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:8000/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:8000/api/pin`
* You should receive a response with a 'bad request' message.

### DELETE requests
* **i.e.** 204 No Content request: `http DELETE localhost:8000/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:8000/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. Updated content from each request will be logged in the first pane of your terminal.
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);
};
55 changes: 55 additions & 0 deletions lib/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
'use strict';

const parseUrl = require('./parse-url.js');
const parseJSON = require('./parse-json.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');
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.write('route not found');
res.end();
})
.catch(err => {
console.error(err);
res.writeHead(400, {
'Content-Type': 'text/plain'
});
res.write('bad request');
res.end();
});
};
};
44 changes: 44 additions & 0 deletions lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use strict';

const storage = {undefined};

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'));
if (!storage[schemaName]) storage[schemaName] = {};

storage[schemaName][item.id] = item;
console.log('storage:', storage);
return Promise.resolve(item);
};

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

var schema = storage[schemaName];
if(!schema) return reject(new Error('schema not found'));

var item = schema[id];
if (!item) return reject(new Error('item not found'));
console.log('storage:', storage);
resolve(item);
});
};

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

var schema = storage[schemaName];
if(!schema) return reject(new Error('schema not found'));

delete schema[id];
console.log('storage:', storage);
resolve();
});
};
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;
};
35 changes: 35 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"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": {
"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