Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Readme #14

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
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"
}
95 changes: 95 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@

# Created by https://www.gitignore.io/api/node,macos

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

Test Data
data/

# End of https://www.gitignore.io/api/node,macos
118 changes: 70 additions & 48 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,70 @@
![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) Lab 11: Single Resource Express API
===

## To Submit this Assignment
* Fork this repository
* Write all of your code in a directory named `lab-` + `<your name>` **e.g.** `lab-brian`
* 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

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

## Description
* 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
### Single Resource API

This single resource API uses the Express framework along with other native Node modules to help me keep track of all of my sweet bikes. It leverages the Bluebird promisifying library on the File System module to add a layer of persistence:

* [markdown-it] - Markdown parser done right. Fast and easy to extend.
* [node.js] - evented I/O for the backend
* [Express] - fast node.js network app framework [@tjholowaychuk]
* [Gulp] - the streaming build system

And of course Dillinger itself is open source with a [public repository][repo]
on GitHub.

### Installation

Dillinger requires [Node.js](https://nodejs.org/) v4+ to run.

Clone down the repo, install the dependencies and devDependencies and start the server.

```sh
$ git clone git@github.com:dkulp23/11-single_resource_express_api.git
$ npm install -d
$ npm start
```

Install and use the HTTPie library to make a POST request to the API:

```sh
$ brew install httpie
$ http POST :3000/api/bike brand="rodriguez" type="sweet fixie brah"
```
To GET the records you've created, you'll first need to copy & past their unique ID:
```
$ http :3000/api/bike/<paste unique id here>
```
And if you want to DELETE it:
```
$ http DELETE :3000/api/bike/<paste id to delete here>
```

Passing 8 tests on 3 defined routes (POST, GET, DELETE). PUT returns 404 error.

Gulpfile default set to run linter and mocha tests.
```sh
$ gulp
```

License
----

MIT


**Free Software, Hell Yeah!**

[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax)


[repo]: <https://github.com/dkulp23/11-single_resource_express_api>
[git-repo-url]: <https://github.com/joemccann/dillinger.git>
[john gruber]: <http://daringfireball.net>
[df1]: <http://daringfireball.net/projects/markdown/>
[markdown-it]: <https://github.com/markdown-it/markdown-it>
[Ace Editor]: <http://ace.ajax.org>
[node.js]: <http://nodejs.org>
[Twitter Bootstrap]: <http://twitter.github.com/bootstrap/>
[jQuery]: <http://jquery.com>
[@tjholowaychuk]: <http://twitter.com/tjholowaychuk>
[express]: <http://expressjs.com>
[AngularJS]: <http://angularjs.org>
[Gulp]: <http://gulpjs.com>
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('lint', function() {
return gulp.src(['**/*.js', '!node_modules'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});

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

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

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

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

module.exports = exports = {};

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

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

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

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

return fs.readFileProm(`${__dirname}/../data/${schemaName}/${id}.json`)
.then( data => {
try {
let foundItem = JSON.parse(data.toString());
return foundItem;
} catch (err) {
return Promise.reject(new createError(500, err.message));
}
})
.catch( err => {
return Promise.reject(new createError(404, err.message));
});
};

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

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

return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`)
.then()
.catch( err => {
return Promise.reject(new createError(500, err.message));
});
};

exports.fetchAllItems = function(schemaName) {
debug('fetchAllItems');

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

return fs.readdirProm(`${__dirname}/../data/${schemaName}`)
.then( items => {
try {
let itemNames = items.join(', ');
return itemNames;
} catch (err) {
return Promise.reject(new createError(500, err.message));
}
})
.catch( err => Promise.reject(new createError(404, err.message)));
};
38 changes: 38 additions & 0 deletions model/bike.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';

const uuid = require('node-uuid');
const debug = require('debug')('bike:bike');
const createError = require('http-errors');
const storage = require(`${__dirname}/../lib/storage.js`);

const Bike = module.exports = function(brand, type) {
debug('bike constructor');

if (!brand) throw createError(400, 'bike brand expected');
if (!type) throw createError(400, 'bike type expected');

this.id = uuid.v1();
this.brand = brand;
this.type = type;
};

Bike.createBike = function(_bike) {
debug('createBike');

try {
let bike = new Bike(_bike.brand, _bike.type);
return storage.createItem('bike', bike);
} catch(err) {
return Promise.reject(err);
}
};

Bike.fetchBike = function(id) {
debug('fetchBike');
return storage.fetchItem('bike', id);
};

Bike.deleteBike = function(id) {
debug('deleteBike');
return storage.deleteItem('bike', id);
};
Loading