// BASE SETUP
// =============================================================================
const apm = require('./apm-app').apm
const express = require('express')
const bodyParser = require('body-parser')
const session = require('express-session')
// const helmet = require('helmet')
const uuid = require('uuid')
const MongoStore = require('connect-mongo')(session)
const cors = require('cors')
const swaggerUi = require('swagger-ui-express')
const swaggerDocument = require('./swagger.json')
const os = require('os')
const fileUpload = require('express-fileupload');
var swaggerJSDoc = require('swagger-jsdoc');
var path = require('path');
// DATABASE CONNECTION
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "[iI]gnored" }]*/
const dbIgnored = require(`${__dirname}/./database/connect`)
// CONFIG
const config = require(`${__dirname}/./config/config`)
// ROUTES
const router = require(`${__dirname}/./routes/router`)
// DEFINE OUR APP USING EXPRESS
const app = express()
app.use(fileUpload());
// let whitelist = ['http://localhost:5005']
let whitelist = config.cors.whitelist
let corsOptions = {
origin: function (origin, callback) {
console.log("Origin---------", origin);
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
},
credentials: true,
preflightContinue: false,
methods: ['GET', 'POST', 'OPTIONS', 'DELETE', 'PUT'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Total-Count', 'x-access-token', 'Content-Range', 'Access-Control-Allow-Methods'],
}
// app.use(cors())
app.options(cors(corsOptions))
// BODYPARSER
// Node.js body parsing middleware.
// Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
app.use(bodyParser.urlencoded({
extended: true,
limit: '50mb'
}))
app.use(bodyParser.json({ limit: '50mb' }))
// HELMET
// Helmet helps you secure your Express apps by setting various HTTP headers
// let helmetOpts = {
// frameguard: false,
// }
// app.use(helmet(helmetOpts))
// Use Mongo Store for Session data storage
const store = new MongoStore({
url: process.env.SESSION_MONGODB_URL || config.db.mongodb_session_store_url,
ttl: config.cookie.validity,
autoRemove: 'native', // Default
})
// EXPRESS-SESSION && MONGOSTORE
// MongoDB session store for Express and Connect
// Simple session middleware for Express
const sess = {
key: config.cookie.name,
secret: config.app.secret,
cookie: {
path: config.cookie.path,
maxAge: config.cookie.validity * 1000,
httpOnly: true,
secure: true
},
resave: false,
saveUninitialized: false,
store: store,
name: config.cookie.name,
genid: function () {
return uuid() // use UUIDs for session IDs
},
}
// Use session
app.use(session(sess))
// session management
session.Session.prototype.login = (req, user, cb) => {
try {
req.session.userInfo = user
req.session.user = user.email
cb()
} catch (error) {
cb(error)
}
}
// SWAGGER
//app.use(config.app.prefix+'/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument))
// swagger definition
var swaggerDefinition = {
info: {
title: 'Node Swagger API',
version: '1.0.0',
description: 'Demonstrating how to describe a RESTful API with Swagger',
},
host: os.hostname,
basePath: '/pnc/rfx/api',
};
// options for the swagger docs
var options = {
// import swaggerDefinitions
swaggerDefinition: swaggerDefinition,
// path to the API docs
apis: ['./routes/*.js'],
};
var swaggerSpec = swaggerJSDoc(options);
app.get('/pnc/rfx/api/swagger.json', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
//app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use(express.static(path.join(`${__dirname}`, 'public')));
app.use('/pnc/rfx/api/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
//End of Swagger defination
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with prefix defined in config
app.use(config.app.prefix, cors(corsOptions), router)
if (process.env.NODE_ENV === 'test')
app.use(config.app.prefix, router)
else
app.use(config.app.prefix, cors(corsOptions), router)
// app.use(config.app.prefix, router)
// app.use(config.app.prefix, router)
// START THE SERVER
app.use(apm.middleware.connect())
// app.use(ErrorHandler)
app.listen((process.env.PORT || config.server.port))
module.exports = app // for testing