Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
2.6 kB
3
Indexable
Never
const express = require('express')
const session = require('express-session')
const MongoDBStore = require('connect-mongodb-session')(session)
const mongoose = require('mongoose')
const cors = require('cors')
require('dotenv').config()

const HttpError = require('./models/http-error')
const userRoutes = require('./routes/users-routes')
const timeEntryRoutes = require('./routes/timeEntrys-routes')
const taskRoutes = require('./routes/tasks-routes')
const reportRoutes = require('./routes/reports-routes')
const receiptRoutes = require('./routes/receipts-routes')
const optionRoutes = require('./routes/options-routes')

const app = express()

const MONGO_URI = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.CLUSTER}/${process.env.DB_NAME}?retryWrites=true&w=majority`

mongoose
  .connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connection Successful!')
  })
  .catch((err) => {
    console.log(err)
  })

const store = new MongoDBStore({
  uri: MONGO_URI,
  collection: 'sessions',
})

app.use(
  session({
    name: 'sid',
    secret: process.env.SESSION_SECRET,
    // resave: true,
    // domain: 'localhost',
    saveUninitialized: false,
    cookie: {
      path: '/',
      // domain: 'localhost',
      // secure: !(
      //   !process.env.NODE_ENV || process.env.NODE_ENV === 'development'
      // ),
      secure: true,
      maxAge: 1000 * 60 * 60 * 24 * 30 * 12,
    },
    store,
  })
)

app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.set('json spaces', 2)
app.use(cors({ origin: '*' }))
app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, authorization'
  )
  res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,PUT,OPTIONS')
  next()
})

// routes
app.use('/api/user', userRoutes)
app.use('/api/time_entry', timeEntryRoutes)
app.use('/api/task', taskRoutes)
app.use('/api/report', reportRoutes)
app.use('/api/receipt', receiptRoutes)
app.use('/api/option', optionRoutes)
app.use((req, res, next) => {
  const error = new HttpError('Could not find this route.', 404)
  throw error
})

// special route to handle errors
app.use((error, req, res, next) => {
  res.status(error.code || 500)
  res.json({ message: error.message || 'An unknown error occurred!' })
})

app.listen(process.env.PORT || 5000, () => {
  const url = `http://localhost:5000/api`
  console.table({ url })
})