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-zachary/.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"
}
129 changes: 129 additions & 0 deletions lab-zachary/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@

# Created by https://www.gitignore.io/api/node,osx,windows,linux

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

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


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

### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk

# End of https://www.gitignore.io/api/node,osx,windows,linux
58 changes: 58 additions & 0 deletions lab-zachary/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Express Single Resource API router w/File Server persistance

This app creates an HTTP server that handles GET, POST, and DELETE to a filesystem-level persistance layer.

# System Requirements

- Terminal.app on macOS or equivalent
- node.js and npm package manager installed


### Installation

Clone the repository to your local server
```sh
https://github.com/zcrumbo/11-single_resource_express_api/tree/lab-zachary
```

Install the dependencies -

```sh
$ npm i
```

[HTTPie](https://httpie.org/) will be required to run the HTTP requests from your terminal window. You will need to install this with [Homebrew][1] on macOS. It is also easier to see the results of all operations by running mocha tests with the command
```sh
$ mocha
```

Start the server

```sh
$ node server.js
```
If you want to use the debug and nodemon modules, run the npm script:
```
npm start
```

### Connecting

If you are using HTTPie, in your terminal window, type the following commands, where '3000' would be replaced with your local environment PORT variable, if configured. Commands can only be sent to the api/bike endpoint
```sh
$ http POST :3000/api/bike name='test name' content='test content' #creates a new bike object and writes it to the fileserver, and returns a unique id
$ http GET localhost:8000/api/bike/sample-id #returns the name and content of a stored bike object
$ DELETE localhost:8000/api/bike/sample-id #deletes the bike file from server storage
```

Sending the following requests to the server will have the results below:

* `GET`: 404 response with 'not found' for valid requests made with an id that was not found
* `GET`: 200 response with an array of all ids if no id was provided in the request
* `GET`: 200 response with a response body for a request made with a valid id
* `POST`: 400 response with 'bad request' if no request body was provided or the body was invalid
* `POST`: 200 response with the body content for a post request with a valid body
* `PUT`: 200 response with body content if a put request was made with an valid id and properly formatted body content
* `PUT`: 400 response with 'bad request' if missing or malformed body data was passed.
[1]:https://brew.sh/

23 changes: 23 additions & 0 deletions lab-zachary/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']);
7 changes: 7 additions & 0 deletions lab-zachary/lib/cors-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

module.exports = function(req, res, next){
res.append('Access-Control-Allow-Origin', '*');
res.append('Access-Control-Allow-Headers', '*');
next();
};
21 changes: 21 additions & 0 deletions lab-zachary/lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

const createError = require('http-errors');
const debug = require('debug')('bike:error-middleware');

module.exports = function(err, req, res, next){
console.error(err.message);

if (err.status){
debug('user error');

res.status(err.status).send(err.name);
next();
return;
}
debug('server error'); //last error handler in app - set generic 500

err = createError(500, err.message);
res.status(err.status).send(err.name);
next();
};
73 changes: 73 additions & 0 deletions lab-zachary/lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
'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'});

//create, fetch delete

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) //whuck? look into this format. return item implied with function.
.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 => {
try{
let item = JSON.parse(data.toString());
return item;
} catch (err) {
return Promise.reject(createError(500, err.message));
}
})
.catch (err => Promise.reject(createError(404, err.message)));
};

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

return fs.readdirProm(`${__dirname}/../data/${schemaName}`)
.then( data => {return data;})
.catch (err => Promise.reject(createError(404, err.message)));
};
exports.deleteItem1 = function(schemaName, id){
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`)
.then( () => id)
.catch( err => Promise.reject(err));
};
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)));//then not necessary
};

exports.availableIDs = function(schemaName) {
return fs.readdirProm(`${__dirname}/../data/${schemaName}`)
.then( files => files.map (name => name.split('.json')[0]))
.catch( err => Promise.reject(createError(404, err.message)));
};


Loading