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
5 changes: 5 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
**/node_modules/*
**/vendor/*
**/*.min.js
**/coverage/*
**/build/*
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"
}
136 changes: 136 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Created by https://www.gitignore.io/api/osx,vim,node,macos,windows

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


### OSX ###

# Icon must end with two \r

# Thumbnails

# Files that might appear in the root of a volume

# Directories potentially created on remote AFP share

### Vim ###
# swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]
# session
Session.vim
# temporary
.netrwhist
*~
# auto-generated tag files
tags

### 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/osx,vim,node,macos,windows
128 changes: 75 additions & 53 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,53 +1,75 @@
![cf](https://i.imgur.com/7v5ASc8.png) 11: Single Resource Express API
======

## Submission Instructions
* fork this repository & create a new branch for your work
* write all of your code in a directory named `lab-` + `<your name>` **e.g.** `lab-susan`
* 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

## Learning Objectives
* students will be able to create a single resource API using the express framework
* students will be able to leverage 3rd party helper modules for debugging, logging, and handling errors

## Requirements

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

#### Feature Tasks
* 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
# Vanilla API Persistence - 09 Lab

## Description:
This app builds out an API where data is stored in the file system. This API stores beer data with the schema of name, style, and IBU.

## API:
The URL endpoint to access the api is `/api/beer`. Using REST architecture the data is read, written and deleted using `GET`, `POST` and `DELETE` requests.

### POST:

```
request.post('localhost:8000/api/beer')
.send({ name: 'Have a Nice Day IPA', style: 'IPA', IBU: '43' })
```

This is a representation of the POST method. You can see that we first make a request to post to
```
localhost:8000
```
with a route of
```
/api/beer
```
Once the connection has bee made we send our beer in
```
.send({ name: 'Have a Nice Day IPA', style: 'IPA', IBU: '43' })
```
format. This will respond with 200 if the request was made or 400 if not.

### GET

```
request.get(`localhost:8000/api/beer?id=${beer.id}`)
```
This is a representation of the GET method. You can see that we first make a request to post to

```
localhost:8000
```
with a route of

```
/api/beer
```

finally with finish the request with reference to a specific id which was generated with uuid

```
?id=${beer.id}
```

This will respond with 200 if the request was made, 404 if not found or 400 if the request was made in wrong format.

### DELETE

```
request.delete(`localhost:8000/api/beer?id=${beer.id}`)
```

This is a representation of the POST method. You can see that we first make a request to post to

```
localhost:8000
```
with a route of

```
/api/beer
```
finally with finish the request with reference to a specific id which was generated with uuid
```
?id=${beer.id}
```

This will respond with 200 if the request was made, 404 if not found or 400 if the request was made in wrong format.
53 changes: 53 additions & 0 deletions lib/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'), { suffix: 'Prom' });
const createError = require('http-errors');
const debug = require('debug')('note: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(err));
};

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(err);
}
})
.catch( () => Promise.reject(createError(404, 'not found')));
};

exports.deleteItem = 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.unlinkProm(`${__dirname}/../data/${schemaName}/${id}.json`)
.then( () => {
try {
console.log('your file was deleted');

} catch (err) {
return Promise.reject(err);
}
})
.catch( err => Promise.reject(err));
};
40 changes: 40 additions & 0 deletions model/beer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use strict';

const uuidv4 = require('uuid/v4');
const createError = require('http-errors');
const debug = require('debug')('beer:beer');
const storage = require('../lib/storage.js');

const Beer = module.exports = function(name, style, IBU) {
debug('beer constructor');

if (!name) throw new Error('expected content');
if (!style) throw new Error('expected content');
if (!IBU) throw new Error('expected content');

this.id = uuidv4();
this.name = name;
this.style = style;
this.IBU = IBU;
};

Beer.createBeer = function(_beer) {
debug('createBeer');

try {
let beer = new Beer(_beer.name, _beer.style, _beer.IBU);
return storage.createItem('beer', beer);
} catch (err) {
return Promise.reject(createError(400, 'bad request'));
}
};

Beer.fetchBeer = function(id) {
debug('fetchBeer');
return(storage.fetchItem('beer', id));
};

Beer.deleteBeer = function(id) {
debug('deleteBeer');
return(storage.deleteItem('beer', id));
};
Loading