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

## Overview

This is a basic Express 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. You should see 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.

### 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']);
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 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)));
};
38 changes: 38 additions & 0 deletions model/pin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'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(err);
}
};

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

Pin.deletePin = function(id) {
debug('deletePin');
return storage.deleteItem('pin', id);
};
41 changes: 41 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"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": "DEBUG='note*' 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",
"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": "^3.9.1",
"gulp-eslint": "^3.0.1",
"gulp-mocha": "^3.0.1",
"mocha": "^3.2.0",
"superagent": "^3.3.0"
}
}
55 changes: 55 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
'use strict';

const express = require('express');
const morgan = require('morgan');
const createError = require('http-errors');
const jsonParser = require('body-parser').json();
const debug = require('debug')('pin:server');

const app = express();
const Pin = require('./model/pin.js');
const PORT = 3000;

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

app.post('/api/pin', jsonParser, function(req, res, next) {
debug('POST: /api/pin');

Pin.createPin(req.body)
.then(pin => res.json(pin))
.catch(err => next(err));
});

app.get('/api/pin', function(req, res, next) {
debug('GET: /api/pin');

Pin.fetchPin(req.query.id)
.then(pin => res.json(pin))
.catch(err => next(err));
});

app.delete('/api/pin', function(req, res, next) {
debug('DELETE: /api/pin');

Pin.deletePin(req.query.id)
.then(() => res.status(204).send())
.catch(err => next(err));
});

// eslint-disable-next-line
app.use(function(err, req, res, next) {
debug('error middleware');
console.error(err.message);

if (err.status) {
res.status(err.status).send(err.name);
return;
}

err = createError(500, err.message);
res.status(err.status).send(err.name);
});

app.listen(PORT, () => {
console.log(`server running: ${PORT}`);
});
Loading