Skip to content

Commit

Permalink
Routes -> Controllers -> Model fo r User Entity and Mongo DB set up (#37
Browse files Browse the repository at this point in the history
)

* Routes -> Controllers -> Model fo r User Entity and Mongo DB set up

* use port 5001 instead of 5000:
https://developer.apple.com/forums/thread/682332

---------

Co-authored-by: Lymeng Naret <lymengnaret@yahoo.com>
  • Loading branch information
AndyLiang1 and NLmeng committed May 27, 2023
1 parent 1b54230 commit b4f0679
Show file tree
Hide file tree
Showing 11 changed files with 465 additions and 12 deletions.
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"dependencies": {
"mongodb": "^5.5.0",
"mongoose": "^7.2.1"
}
}
1 change: 1 addition & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
Expand Down
21 changes: 21 additions & 0 deletions server/config/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require('dotenv').config()

const MONGO_USERNAME = process.env.MONGO_USERNAME || ''
const MONGO_PASSWORD = process.env.MONGO_PASSWORD || ''
const MONGO_URI = `mongodb+srv://${MONGO_USERNAME}:${MONGO_PASSWORD}@cluster0.4bflh41.mongodb.net/BugStormDB?retryWrites=true&w=majority`
const SERVER_PORT = process.env.PORT ? Number(process.env.PORT) : 5001
const ENV = process.env.ENV || ''
const JWT_SECRET = process.env.JWT_SECRET || ''

const config = {
mongo: {
uri: MONGO_URI,
},
server: {
port: SERVER_PORT,
env: ENV,
JWT_SECRET,
},
}

module.exports = config
9 changes: 9 additions & 0 deletions server/controllers/Controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const UserController = require('./UserController')

const userController = new UserController()

const controllers = {
userController: userController,
}

module.exports = controllers
53 changes: 53 additions & 0 deletions server/controllers/UserController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const UserModel = require('../models/UserModel')

class UserController {
constructor() {}

async getAll() {
try {
const users = await UserModel.find()
return users
} catch (error) {
console.error('Error while retrieving users:', error)
throw error
}
}

async createUser(userData) {
try {
const newUser = await UserModel.create(userData)
return newUser
} catch (error) {
console.error('Error while creating user:', error)
throw error
}
}

async updateUser(userId, updateData) {
try {
const updatedUser = await UserModel.findByIdAndUpdate(
userId,
updateData,
{
new: true, // Return the updated user
},
)
return updatedUser
} catch (error) {
console.error('Error while updating user:', error)
throw error
}
}

async deleteUser(userId) {
try {
const deletedUser = await UserModel.findByIdAndRemove(userId)
return deletedUser
} catch (error) {
console.error('Error while deleting user:', error)
throw error
}
}
}

module.exports = UserController
31 changes: 27 additions & 4 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,34 @@
const express = require('express')
const mongoose = require('mongoose')

const UserRoute = require('./routes/UserRoute')
const config = require('./config/config')
const app = express()
const port = 5000
app.use(express.json())

const apiRouter = express.Router()
app.use('/api', apiRouter)

const userRoute = new UserRoute()
userRoute.initRoutes(apiRouter)

app.get('/', (req, res) => {
res.send('Hello, world!')
})

app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
const connectDB = async () => {
try {
await mongoose.connect(config.mongo.uri)
startServer()
} catch (err) {
console.error(err)
}
}

const startServer = () => {
app.listen(config.server.port, () => {
console.log(`Server is running on port ${config.server.port}`)
})
}

connectDB()
18 changes: 18 additions & 0 deletions server/models/UserModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
})

module.exports = mongoose.model('User', userSchema)
2 changes: 2 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.2.1",
"express": "^4.18.2",
"mongodb": "^5.5.0",
"mongoose": "^7.2.1",
"prettier": "^2.8.8",
"prop-types": "^15.8.1",
"yarn": "^1.22.19"
Expand Down
27 changes: 27 additions & 0 deletions server/routes/UserRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const express = require('express')
const controllers = require('../controllers/Controllers')

class UserRoute {
constructor() {
this.router = express.Router()
// the this.getAll.bind(this) is basically saying
// when I hit /api/example in a get request, I am going
// to call the getAll function
this.router.get('', this.getAll.bind(this))
}

initRoutes(apiRouter) {
apiRouter.use('/user', this.router)
}

async getAll(req, res) {
try {
const response = await controllers.userController.getAll()
res.json(response)
} catch (err) {
console.error(err)
}
}
}

module.exports = UserRoute
Loading

0 comments on commit b4f0679

Please sign in to comment.