Skip to content

Commit

Permalink
solution 4.15: bloglist expansion, step3
Browse files Browse the repository at this point in the history
  • Loading branch information
patchamama committed Sep 11, 2023
1 parent 28c0b06 commit 5ec001c
Show file tree
Hide file tree
Showing 9 changed files with 573 additions and 33 deletions.
2 changes: 2 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const express = require('express')
const app = express()
const cors = require('cors')
const BlogsRouter = require('./controllers/blogs')
const usersRouter = require('./controllers/users')
const middleware = require('./utils/middleware')
const logger = require('./utils/logger')
const mongoose = require('mongoose')
Expand All @@ -26,6 +27,7 @@ app.use(express.json())
app.use(middleware.requestLogger)

app.use('/api/blogs', BlogsRouter)
app.use('/api/users', usersRouter)

app.use(middleware.unknownEndpoint)
app.use(middleware.errorHandler)
Expand Down
27 changes: 27 additions & 0 deletions controllers/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const bcrypt = require('bcrypt')
const usersRouter = require('express').Router()
const User = require('../models/user')

usersRouter.post('/', async (request, response) => {
const body = request.body

const saltRounds = 10
const passwordHash = await bcrypt.hash(body.password, saltRounds)

const user = new User({
username: body.username,
name: body.name,
passwordHash,
})

const savedUser = await user.save()

response.json(savedUser)
})

usersRouter.get('/', async (request, response) => {
const users = await User.find({})
response.json(users)
})

module.exports = usersRouter
4 changes: 4 additions & 0 deletions models/blog.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ const blogSchema = new mongoose.Schema({
type: Number,
default: 0,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
})

blogSchema.set('toJSON', {
Expand Down
33 changes: 33 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')

const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
},
name: String,
passwordHash: String,
notes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Blog',
},
],
})

userSchema.plugin(uniqueValidator)

userSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
// the passwordHash should not be revealed
delete returnedObject.passwordHash
},
})

const User = mongoose.model('User', userSchema)

module.exports = User
Loading

0 comments on commit 5ec001c

Please sign in to comment.