Skip to content
This repository has been archived by the owner on Sep 7, 2022. It is now read-only.

remove old dependency #15

Open
wants to merge 164 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
164 commits
Select commit Hold shift + click to select a range
94ffa48
Initial commit.
Feb 22, 2016
3616736
Applied linter suggestions for JavaScript Standard style (http://stan…
rkorsak Feb 22, 2016
6016204
Update LICENSE.md
lindybrandon Feb 23, 2016
2c47cdd
Update README.md
lindybrandon Feb 23, 2016
1497be2
Update README with dependency info
rkorsak Feb 23, 2016
d7bbfd2
Update CreditOffersClient with style tweaks and proper error reportin…
rkorsak Feb 23, 2016
5af16a7
Added content to the architecture section of the README
rkorsak Feb 23, 2016
a1cb738
Added new images and json for credit offers.
Feb 24, 2016
128e858
Merge pull request #1 from capitalone/task.new-credit-offers-json-and…
rkorsak Feb 24, 2016
2a06f72
Add 2-legged OAuth support to Credit Offers
rkorsak Feb 24, 2016
ceaf15a
Fixed a bad image URL in the mock data.
Feb 24, 2016
b1ad8c8
Merge pull request #2 from capitalone/task.2-legged-oauth
Feb 24, 2016
3d88990
Replaced config.js with config.js.sample and added config.js to .giti…
Feb 24, 2016
b5d5047
Updated the README with info about config.js.sample.
Feb 24, 2016
b154f40
Merge pull request #3 from capitalone/task.config.js.sample
rkorsak Feb 24, 2016
178bfce
Updated config.js.sample link to not try and display as image.
Feb 24, 2016
01c8adf
Fix inverted token logic
rkorsak Feb 24, 2016
15b9770
Added helmet to protect from well-known web vulnerabilities.
Feb 25, 2016
78b3dc4
Added CSRF protection to the credit offers form.
Feb 25, 2016
c5d7544
Merge pull request #4 from capitalone/feature.security-updates
rkorsak Feb 25, 2016
f1ac399
Update README with best practices section
rkorsak Feb 26, 2016
5599575
Fix "targeted-products-offer" URL mistake
rkorsak Mar 2, 2016
31b66fc
Make birth date optional in UI
rkorsak Mar 2, 2016
c87cbe1
Added files via upload
lindybrandon Mar 3, 2016
d60c239
Removed mock Credit Offers API and updated reference app to point to …
Mar 5, 2016
2736937
Merge pull request #5 from capitalone/task.use-sandbox
rkorsak Mar 5, 2016
b350127
Update package.json to match SwiftID
rkorsak Mar 9, 2016
e56bda3
Merge pull request #6 from capitalone/task.update-package-file
Mar 9, 2016
120ebf1
Include CLA and Open Source Code of Conduct
SanthiSridharan Mar 10, 2016
9f38b20
Reformat notices txt file
rkorsak Mar 28, 2016
76f31fd
Use more restrictive version matching in package.json
rkorsak Apr 4, 2016
9bfe7e6
fix UI text per affiliates requirements
Oct 14, 2016
bfad582
fix UI text better
Oct 14, 2016
3467bb6
Merge pull request #7 from Bradamant3/UI_strings
rkorsak Oct 18, 2016
6aad235
Updated package.json to 2.0.0
rkorsak Oct 18, 2016
7a5792e
Re-added mock API
rkorsak Oct 18, 2016
af3255b
Update API version to 2
rkorsak Oct 18, 2016
3b5f97c
Update default API version in config
rkorsak Oct 18, 2016
38aa804
Parse errors for all 4xx and 5xx responses
rkorsak Oct 18, 2016
986f40f
Moved response parsing out of the _sendRequest function
rkorsak Oct 18, 2016
2c639a5
Updated name, docs, and implementation of pre-qual
rkorsak Oct 18, 2016
9940414
Adjusted client to always use JSON
rkorsak Oct 18, 2016
de1a4d0
Updated mock API with new prequal response
rkorsak Oct 18, 2016
416a6ef
Updated client response parsing
rkorsak Oct 18, 2016
f30f302
Fix mock API prequal route
rkorsak Oct 18, 2016
f879016
Update route and views for prequal
rkorsak Oct 18, 2016
e2a7a8b
Fix display name in mock data
rkorsak Oct 18, 2016
584b7d8
Add prequal ack to client
rkorsak Oct 18, 2016
6fd4f98
Prequal ack in mock API and UI
rkorsak Oct 19, 2016
678f91f
Refactored API client into multiple files
rkorsak Oct 21, 2016
6e6c0d6
Add product listings API client
rkorsak Oct 21, 2016
59a50a2
Update Mock API with product routes
rkorsak Oct 26, 2016
5afd69b
Added bootstrap in npm, moved public files
rkorsak Oct 26, 2016
c44fc7d
Add Font Awesome
rkorsak Oct 26, 2016
8719c74
Add favicon
rkorsak Oct 26, 2016
caac5f6
Update products API
rkorsak Oct 26, 2016
5aea263
First major UI update for cards
rkorsak Oct 26, 2016
f12a508
Fixed pagination query string in product api client
rkorsak Oct 26, 2016
2514fc9
UI adjustments
rkorsak Oct 26, 2016
4b4845a
UI fixes and small update to prequal results
rkorsak Oct 26, 2016
d99d571
Simplified and enhanced product generation
rkorsak Oct 28, 2016
2a5f0f0
Update mock API products
rkorsak Oct 28, 2016
d4066d9
Run products through a view model before displaying
rkorsak Oct 28, 2016
befd2d5
Fix a bad string in mock products
rkorsak Oct 28, 2016
8a5aaf4
Change the marketing copy sample size
rkorsak Oct 28, 2016
d652e30
Style updates, collapsible marketing copy
rkorsak Oct 28, 2016
de66de8
Switch to just lorem ipsum copy for now
rkorsak Oct 28, 2016
0b14709
Display API errors in index
rkorsak Oct 28, 2016
47e5455
Removed non-lorem-ipsum text
rkorsak Nov 2, 2016
bb76dc4
Dropping the product display limit to 10
rkorsak Nov 2, 2016
0144a27
Updated routes and mock API to use correct values for product types i…
rkorsak Nov 14, 2016
8f3024d
Full response body logging
rkorsak Nov 14, 2016
cdccabf
Explicitly pull only the required customer fields for prequal
rkorsak Nov 14, 2016
eeaa53a
Fixed incorrect setting of response status
rkorsak Nov 14, 2016
53f2eb0
Basic server-side validation of prequal info
rkorsak Nov 14, 2016
6d24dba
Added HTML sanitization package for displaying html from the API
rkorsak Nov 15, 2016
af59fd0
Added HTML entity decoding package
rkorsak Nov 15, 2016
b32db3e
Display sanitized HTML from the API responses
rkorsak Nov 15, 2016
3631893
Refactored API client for more accurate logging and less repetition
rkorsak Nov 15, 2016
485c2ed
Fixed productName in prequal view model
rkorsak Nov 15, 2016
1e4a58a
Placeholder card image
rkorsak Nov 15, 2016
504d7f1
Display product name as a link if a URL is available
rkorsak Nov 15, 2016
f8b1a44
Tiny jade syntax fix
rkorsak Nov 15, 2016
d84ed71
Display server-side validation errors in UI
rkorsak Nov 15, 2016
360178f
Fix regex for tax ID
rkorsak Nov 15, 2016
2f6994b
Refactor routing to use a single shared API client
rkorsak Nov 15, 2016
a6eed21
Updated README file
rkorsak Nov 16, 2016
b455983
Add Apache License text to www file
rkorsak Nov 16, 2016
a2cb352
Regenerated license notices as markdown
rkorsak Nov 16, 2016
0b8e9c5
More README updates
rkorsak Nov 16, 2016
e6ebbd1
Added client code for /credit-offers/products
rkorsak Nov 16, 2016
cff9ba8
Removed the mock API
rkorsak Nov 16, 2016
79ba9e9
Fixed a README mistake in the run instructions
rkorsak Nov 16, 2016
0f26f54
Added prequal summary to client
rkorsak Nov 18, 2016
e54f183
Added prequal summary to UI
rkorsak Nov 18, 2016
04a2856
OAuth debug log
rkorsak Nov 18, 2016
eed41ec
Updated the README with prequal summary info
rkorsak Nov 18, 2016
733d4f3
Switched dependencies to exact versions
rkorsak Nov 22, 2016
3c75c68
add config detail in readme
Nov 28, 2016
480528c
update oauth token endpoint
Nov 28, 2016
6f37269
Merge pull request #8 from Bradamant3/readme-update
rkorsak Nov 28, 2016
71534ef
Normalize card image sizes
rkorsak Nov 30, 2016
94ef8df
Use any available card image for both APIs
rkorsak Nov 30, 2016
7b83011
Removed extra logging in the view
rkorsak Nov 30, 2016
c4bc3c4
Prefer card art images over card name
rkorsak Nov 30, 2016
f5f7c73
Changed 'type' back to 'imageType' for products
rkorsak Dec 1, 2016
ea5d7c3
Merge pull request #9 from capitalone/v2
rkorsak Dec 1, 2016
73986da
Made address type optional
rkorsak Dec 1, 2016
3c3fed9
Add acknowledgement indicator to the app
rkorsak Dec 9, 2016
c09222e
Added option to view all cards
rkorsak Dec 9, 2016
10b0f25
Add keyword tooltip on image hover
rkorsak Dec 9, 2016
f5ccfe2
Add additional info to each product
rkorsak Dec 15, 2016
ca3a24b
Added modal to display raw JSON per product
rkorsak Jan 3, 2017
63fb0a8
Added raw JSON modal to pre-qual results
rkorsak Jan 3, 2017
aaa9b09
Added SPDX statements to license headers
rkorsak Jan 27, 2017
be224b6
Update all copyright years in source code to 2017
pamtaro Apr 4, 2017
eaa7c76
Update product & preQual w/ latest from API models;
pamtaro Apr 4, 2017
457725e
Merge pull request #11 from capitalone/v2.1
mahzooey Apr 11, 2017
d380d03
Update README.md
reign-the-coder Jul 12, 2017
bdf7227
Update README.md
reign-the-coder Jul 12, 2017
e772c83
Update config.js.sample
reign-the-coder Jul 13, 2017
7007cdf
Updated apply now wont work in SB mode
Jul 14, 2017
83e3737
Update README.md
reign-the-coder Jul 14, 2017
7265f7c
Update preQualProduct.js
reign-the-coder Jul 14, 2017
e481a05
COFFERS-459 update reference app w v3 changes
reign-the-coder Jul 17, 2017
3114fa4
Merge branch 'master' of https://github.com/capitalone/CreditOffers-A…
reign-the-coder Jul 17, 2017
0ff3e78
Removing debugging statements
reign-the-coder Jul 17, 2017
993a598
Merge branch 'master' of https://github.com/capitalone/CreditOffers-A…
neetiagarwal Jul 17, 2017
12f9972
Changes api version to v3
neetiagarwal Jul 17, 2017
08eff79
Added APR information on prequalification and disabled Apply Now link…
reign-the-coder Jul 17, 2017
98b4fb8
Adding more files to gitignore
reign-the-coder Jul 17, 2017
14ef895
Adding APR to prequal and disabling Apply Now link
reign-the-coder Jul 17, 2017
8c514ce
Merge branch 'master' of https://github.com/capitalone/CreditOffers-A…
reign-the-coder Jul 17, 2017
a8be93b
Update README.md
reign-the-coder Jul 17, 2017
88f9393
Terms is no longer in prequalification products object
reign-the-coder Jul 17, 2017
ed69749
Merge branch 'master' of https://github.com/capitalone/CreditOffers-A…
reign-the-coder Jul 17, 2017
47f10b6
added login button
Oct 17, 2017
21c378d
login modal form
Oct 18, 2017
c4f69cf
login modal sandbox defaults
Oct 27, 2017
587e389
handle signin/signout
Oct 27, 2017
1bb9d71
handle prefill
Oct 27, 2017
1304328
Merge pull request #1 from Professional-Services/feature-login
Oct 27, 2017
98a0770
ajax support for invalid form
Oct 31, 2017
645b79d
cleanup and pq ajax removal
Nov 2, 2017
1a1e31e
test on heroku
Nov 6, 2017
1d8e826
config
Nov 6, 2017
df74266
QA config
Nov 6, 2017
f3d41bb
finalized fixes for prefill and r&r
Nov 8, 2017
7a593ae
ignore config.js again
Nov 8, 2017
3d5f50d
remove config.js again
Nov 8, 2017
d33d76a
update dependency licenses
Nov 8, 2017
dde49af
update ejs package
Dec 5, 2017
2a1d063
Remove PQ Summary
Dec 5, 2017
ef0f4a6
cleanup js file
Dec 5, 2017
59d8253
spacing on prefil modal buttons and merge fixes
Dec 5, 2017
80fd3b8
Merge pull request #1 from mhogan42/feature-master
mhogan42 Dec 5, 2017
e8cdca2
remove unnecessary oauth host
Jan 16, 2018
c428d28
Default PQ user info if signed in
Feb 6, 2018
d5ea07f
display key in sanbox
Feb 7, 2018
afa1a92
show applicant details in modal
Feb 7, 2018
ae63fff
line fixes for jade
Feb 14, 2018
7a71c56
dateOfBirth for applicantDetailsKey
Feb 23, 2018
419719d
handle when no bankAccountSummaryOptions
Mar 12, 2018
6dc8989
remove moment dependency
Mar 12, 2018
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
46 changes: 46 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Ignore config files. Users should alter the sample.
config.js

# Thumbs
Thumbs.db

# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# 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 REPL history
.node_repl_history

# Optional IDEA file
.idea

# Package-lock JSON
package-lock.json
2 changes: 1 addition & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright {yyyy} {name of copyright owner}
Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
90 changes: 88 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,89 @@
# Credit Offers API Reference App
# Credit Offers API Reference Application Code

Stuff here about how to build and use this
Credit Offers is a card acquisition service that provides prequalified credit offer listings based on end customer provided information. Affiliates are able to provide these offers directly without need of a web redirect. If a prequalified offer is not available, a default offer is returned by us.

## Software Requirements Including version
This is version 2.0 of the Credit Offers API Reference Application Code. For software requirements, see Build/Install Instructions below.

This reference app illustrates the use of the Credit Offers API to

* Retrieve and display card products (Business or Consumer) using the `/credit-offers/products/cards/{cardType}` endpoint
* Collect customer information and retrieve a list of targeted product offers for display using the `/credit-offers/prequalifications` endpoint
* Send acknowledgement to Capital One that the targeted product offers have been displayed using the `/credit-offers/prequalifications/{prequalificationId}` endpoint
* Retrieve and display prequalification summary info using the `/credit-offers/prequalifications-summary` endpoint
* Exemplify signing in and submitting example user data to the `/credit-offers/prefill-acceptance` endpoint

Some additional API features that are **not** directly illustrated by this app include:

* Using the `limit` and `offset` parameters to retrieve multiple pages of products
* Using the `/credit-offers/products` endpoint to retrieve summaries of *all* products
* Using the `/credit-offers/products/cards` endpoint to retrieve summaries of all card products
* Using the `/credit-offers/products/cards/{cardType}/{productId}` endpoint to retrieve information about a single specific card product

If you encounter any issues using this reference code, please submit them in the form of GitHub issues.

## Build/Install Instructions
### Dependencies
* [Node.js](https://nodejs.org) 4.X or higher

All other dependencies are loaded with [npm](https://www.npmjs.com/). All dependencies are cross-platform. Notable dependencies are listed below.
* [express](http://expressjs.com/) - Minimalist web framework for Node.js

### config.js
You'll need to set up your `config.js` file before you can run the app.

* Create this file by copying and renaming [config.js.sample](https://github.com/capitalone/CreditOffers-API-reference-app/blob/master/config.js.sample). Be careful not to put `config.js` into version control. (We've added it to the repository's `.gitignore` for you.)
* Make sure that you've registered an app on [Capital One's developer portal](https://developer.capitalone.com/).
* Edit the `clientID` and `clientSecret` values in `config.js` to specify the **Client ID** and **Client Secret** that were provided when you registered the app.

### Start the app
From the project root:

`npm install`
`npm start`

### Try it out

Navigate to http://localhost:3000. This will retrieve a list of Consumer card products from the API and display simple information about each. From here, you can try a few simple things:

* Toggle the card type to 'Business' to request and display a list of business card products from the API
* Click on the 'Find Pre-Qualified Offers' button to launch a simple customer information form and test out the pre-qualification API behavior. The results screen will also perform two asynchronous calls:
* POST to `/credit-offers/prequalifications/{prequalificationId}` to acknowledge that the results were displayed to the customer
* GET from the `/credit-offers/prequalifications-summary` endpoint to display simple pre-qualification statistics at the bottom of the page
* Click on the 'Sign in' button and use prepared credentials to simulate a session. Now, click on any products 'Apply Now' button. A confirmation window will launch, asking you to confirm whether you would like to prefill application information. Confirming will initiate a POST request to the `/credit-offers/prefill-acceptance` endpoint and append the returned applicantDetailsKey to the application link.
* username / password
* jsmith / Reference@123
* rhubbard / Reference@123

#### A note about errors

For demonstration purposes, API and server-side validation errors are displayed in an error page in the UI. A full production-ready application should have more robust error handling, and keep a smooth user experience.

### Viewing more details

To get a deeper look at the messages being passed, start the app with the following command `DEBUG=credit-offers:* NODE_DEBUG=request npm start`. This will activate detailed debug logging to the console, showing the details of the request to the API and the response received.

## Best Practices
This application makes use of the [helmet](https://www.npmjs.com/package/helmet) library for safer http headers, the [csurf](https://www.npmjs.com/package/csurf) library to avoid cross-site request forgery attacks, the [express-validator](https://www.npmjs.com/package/express-validator) library to validate customer info on the server side, and the [sanitize-html](https://www.npmjs.com/package/sanitize-html) library to safely sanitize values from the API before displaying them as HTML to the user. However, when developing and hosting a real world application, make sure to be aware of the [security](http://expressjs.com/en/advanced/best-practice-security.html) and [performance](http://expressjs.com/en/advanced/best-practice-performance.html) best practices for the Express framework. In particular, hosting with TLS is strongly recommended and free certificates can be acquired at https://letsencrypt.org/.

## Architecture
This is a [Node.js](https://nodejs.org) 4.x and higher app built with [Express](http://expressjs.com/) 4.13.1. Because of the simple nature, there is no session management or data persistence.

The Node.js https library is verbose and repetitive for our narrow use case, so we also used [request](https://github.com/request/request) for calls to the Credit Offers API.

The application structure follows the pattern generated by the [Express application generator](http://expressjs.com/en/starter/generator.html).

## Roadmap
This reference app code is intended as a starting place for developers who want to use the Credit Offers API. As such, it will be updated with new functionality only when the Credit Offers API is updated with new functionality.

## Contributors
We welcome your interest in Capital One’s Open Source Projects (the “Project”). Any Contributor to the Project must accept and sign a CLA indicating agreement to the license terms. Except for the license granted in this CLA to Capital One and to recipients of software distributed by Capital One, You reserve all right, title, and interest in and to your Contributions; this CLA does not impact your rights to use your own contributions for any other purpose.

##### [Link to Agreement] (https://docs.google.com/forms/d/19LpBBjykHPox18vrZvBbZUcK6gQTj7qv1O5hCduAZFU/viewform)

This project adheres to the [Open Source Code of Conduct][code-of-conduct]. By participating, you are expected to honor this code.

[code-of-conduct]: http://www.capitalone.io/codeofconduct/

### Contribution Guidelines
We encourage any contributions that align with the intent of this project and add more functionality or languages that other developers can make use of. To contribute to the project, please submit a PR for our review. Before contributing any source code, familiarize yourself with the Apache License 2.0 (license.md), which controls the licensing for this project.
108 changes: 108 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
Copyright 2017 Capital One Services, LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.

SPDX-Copyright: Copyright (c) Capital One Services, LLC
SPDX-License-Identifier: Apache-2.0
*/

var express = require('express')
var path = require('path')
var favicon = require('serve-favicon')
var logger = require('morgan')
var cookieParser = require('cookie-parser')
var cookieSession = require('cookie-session')
var bodyParser = require('body-parser')
var expressValidator = require('express-validator')
var helmet = require('helmet')
var csrf = require('csurf')

var validation = require('./validation')

var CreditOffers = require('./creditoffers')
var oauth = require('./oauth')
var index = require('./routes/index')
var offers = require('./routes/offers')

var app = express()
var config = require('./config')

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: false
}))
app.use(expressValidator({
customValidators: validation.customValidators
}))
app.use(cookieParser())
app.use(cookieSession({
name: 'session',
secret: "b34ejefAt7a3eme5e7paCrEgatadEqEs",

// Cookie Options
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))
app.use(express.static(path.join(__dirname, 'public')))
// Include the bootstrap package
app.use('/css', express.static(path.join(__dirname, 'node_modules/bootstrap/dist/css')))
app.use('/js', express.static(path.join(__dirname, 'node_modules/bootstrap/dist/js')))
// Include font awesome
app.use('/css', express.static(path.join(__dirname, 'node_modules/font-awesome/css')))
app.use('/fonts', express.static(path.join(__dirname, 'node_modules/font-awesome/fonts')))

app.use(helmet())

// Initialize the routing
var client = new CreditOffers(config.creditOffers.client, oauth(config.creditOffers.oauth))
app.use('/', index(client))
app.use('/offers', offers(client))

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
})

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500)
res.render('error', {
message: err.message,
error: err
})
})
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500)
res.render('error', {
message: err.message,
error: {}
})
})

module.exports = app
104 changes: 104 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#!/usr/bin/env node
/*
Copyright 2017 Capital One Services, LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
*/

/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('credit-offers:server');
var http = require('http');

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
Loading