Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
May 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
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"
}
}
Comment on lines +1 to +6
Copy link
Member

@NLmeng NLmeng May 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

might have accidentally install the dependencies in root. should be fine though. will be resolved in my pr

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh yea oops I only removed the node module

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
Comment on lines +1 to +6
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i changed this to use port 5001, some mac has problems with port 5000 https://developer.apple.com/forums/thread/682332

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No problem :)

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