Skip to content

Instantly share code, notes, and snippets.

@aleksejkozin
Last active December 2, 2021 16:40
Show Gist options
  • Save aleksejkozin/d0c7af3c71eaba942c2b8ad68d0f7c77 to your computer and use it in GitHub Desktop.
Save aleksejkozin/d0c7af3c71eaba942c2b8ad68d0f7c77 to your computer and use it in GitHub Desktop.
import {connect} from 'mongoose'
import {messages} from './messages'
connect(
// Do not commit prod credentials to git tho
'mongodb+srv://NToss:aKmgd43Sf1@cluster0.bkca8.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
)
.then(() => console.log('Successfully connected to the database'))
.catch(err => console.log('Could not connect to the database. Error...', err))
const app = express()
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.get('/', (req, res) => res.json({message: 'Server is running :D'}))
// Attaching service to /messages route
app.use('/messages', messages)
// Centralize error handling.
// Each route should call .catch(next) tho in order for it to work.
// Will be much simpler in express 5.0.0.
// But now you need to call next() on an async exception
app.use(
(err, req, res, next) =>
res.status(500).json({error: err.message})
)
const PORT = 8080
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment