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 lab-hawa/.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"
}
117 changes: 117 additions & 0 deletions lab-hawa/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Created by https://www.gitignore.io/api/ma,node,macos,windows,linux

#!! ERROR: ma is undefined. Use list command to see defined gitignore types !!#

node_modules/

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



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


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


### 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*
119 changes: 119 additions & 0 deletions lab-hawa/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
__Single Resource Express API__
======
This server-side application creates a single resource REST API implementing [Express.js](http://expressjs.com/) which allows the user to POST, GET and DELETE requests via the terminal.

---
## Cloning the Repository
Clone down this repository: https://github.com/abdih17/11-express_single_resource_api.git

```
$ git clone https://github.com/abdih17/11-express_single_resource_api.git
```

## Installation

Install any dependency from the `package.json` file into the project root
directory, and start the server.

```sh
$ cd lab-hawa
$ npm i
$ npm start
```

You should receive the following result: `Server up: 3000` or whichever port number have preset in your environment variables.

## Set Up Necessary Directories

Before writing our POST requests in our server, we need to create a directory were the data can be stored. In order to do so, you need to create a folder called 'spiritAnimal', inside of a folder called 'data'

```sh
$ cd lab-hawa
$ mkdir data
$ cd data
$ mkdir spiritAnimal
```

## POST, GET, and DELETE Requests

**POST Request:**
The POST request must include name, spiritAnimal, and spiritAnimalName parameters.

>**In an new terminal window, send a POST request by using the command:**
>`http POST localhost:3000/api/spiritAnimal name=<name> spiritAnimal=<creature> spiritAnimalName=<creature name>`.

A successful response should return a JSON object with values you entered along with a unique **id number** and a status code of **200**. This will also create a new `.json` file into the `data` folder with the `id` as the file name.

Here's an example of a POST request and the successful response:
```
$ http POST localhost:3000/api/spiritAnimal name="Hawa" spiritAnimal="Pink Dragon" spiritAnimalName="Simba"

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 115
Content-Type: application/json; charset=utf-8
Date: Tue, 20 Dec 2016 18:10:12 GMT
ETag: W/"73-9UbvR26KBJnG17ThN4YOOg"
X-Powered-By: Express

{
"id": "8cd78500-c6df-11e6-aae4-8d9fefc8cd83",
"name": "Hawa",
"spiritAnimal": "Pink Dragon",
"spiritAnimalName": "Simba"
}
```

**GET Request:**

>**In a new terminal window, send a `GET` request by using the command:**
>`http localhost:3000/api/spiritAnimal?id=<id>`.

A successful response should return a JSON object with a status of **200**.

Using the unique **id** number from, here's an example of a successful GET request and response:
```
$ http localhost:3000/api/spiritAnimal?id=8cd78500-c6df-11e6-aae4-8d9fefc8cd83

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 115
Content-Type: application/json; charset=utf-8
Date: Tue, 20 Dec 2016 18:13:52 GMT
ETag: W/"73-CYiHeGR1flyV0Ocsh21Z9w"
X-Powered-By: Express

{
"id": "8cd78500-c6df-11e6-aae4-8d9fefc8cd83",
"name": "Hawa",
"spiritAnimal": "Pink Dragon",
"spiritAnimalName": "Simba"
}

```

**DELETE Request:**

>**In a new terminal window, send a `DELETE` request by using the command:**
>`http DELETE localhost:8000/api/spiritAnimal?id=<id>`

The a successful response should return a **204** status code with no content.
Here's a successful DELETE request and response (which returns no content):
```
$ http DELETE localhost:3000/api/spiritAnimal?id=8cd78500-c6df-11e6-aae4-8d9fefc8cd83

HTTP/1.1 204 No Content
Connection: keep-alive
Date: Tue, 20 Dec 2016 18:25:21 GMT
ETag: W/"0-1B2M2Y8AsgTpgAmY7PhCfg"
X-Powered-By: Express



```

## Exit the Server

Go back to the terminal where your server is running with the port number and press **Ctrl+C** in order to exit the server.

---
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"045b6010-c6e0-11e6-a21f-8f6373b2c0e4","name":"Hawa","spiritAnimal":"Pink Dragon","spiritAnimalName":"Simba"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"677dcb10-c6e0-11e6-a21f-8f6373b2c0e4","name":"Harry Potter","spiritAnimal":"Hippogriff","spiritAnimalName":"Hippogriff The 3rd"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"74c02f10-fd28-11e6-97de-077823d073bd","name":"Hawa","spiritAnimal":"pink dragon","spiritAnimalName":"Simba"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"9acf39d0-fd28-11e6-bf1b-1b6f5f187e5c","name":"Hawa","spiritAnimal":"pink dragon","spiritAnimalName":"Simba"}
25 changes: 25 additions & 0 deletions lab-hawa/gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict';

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

//TODO:watch each individual file??

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/**'], ['test', 'lint']);
});

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

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

module.exports = exports = {};

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

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 -- storage.js');

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 -- storage.js');

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

return fs.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`)
.then(() => Promise.resolve())
.catch(err => Promise.reject(createError(404, err.message)));
};
43 changes: 43 additions & 0 deletions lab-hawa/model/spiritAnimal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'use strict';

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

const SpiritAnimal = module.exports = function(name, spiritAnimal, spiritAnimalName) {
debug('spirit animal constructor');

if (!name) throw createError(400, 'expected name');
if (!spiritAnimal) throw createError(400, 'expected spirit animal');
if (!spiritAnimalName) throw createError(400, 'expected favorite animal');

this.id = uuid.v1();
this.name = name;
this.spiritAnimal = spiritAnimal;
this.spiritAnimalName = spiritAnimalName;
};
//this is a wrapper method. Static = not instantiated on the object. If we console log 'this',
//we get back a constructor averse a the properties of a constructor.
SpiritAnimal.createSpiritAnimal = function (_spiritAnimal) {
debug('createItem -- spiritAnimal.js');

try {
let spiritAnimal = new SpiritAnimal(_spiritAnimal.name, _spiritAnimal.spiritAnimal, _spiritAnimal.spiritAnimalName);
return storage.createItem('spiritAnimal', spiritAnimal);
} catch (err) {
return Promise.reject(err);
}
};

SpiritAnimal.fetchSpiritAnimal = function(id) {
debug('fetchSpiritAnimal');

return storage.fetchItem('spiritAnimal', id);
};

SpiritAnimal.deleteSpiritAnimal = function(id) {
debug('deleteSpiritAnimal');

return storage.deleteItem('spiritAnimal', id);
};
Loading