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

adding server #96

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
5 changes: 5 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PORT=3002
DB_USER=test
DB_PASSWORD=test
DB_NAME=wabala
JWT_SECRET=jopa
110 changes: 110 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import User from '../models/User.js'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'

// Register user
export const register = async (req, res) => {
try {
const { username, password } = req.body

const isUsed = await User.findOne({ username })

if (isUsed) {
return res.json({
message: 'Данный username уже занят.',
})
}

const salt = bcrypt.genSaltSync(10)
const hash = bcrypt.hashSync(password, salt)

const newUser = new User({
username,
password: hash,
})

const token = jwt.sign(
{
id: newUser._id,
},
process.env.JWT_SECRET,
{ expiresIn: '30d' },
)

await newUser.save()

res.json({
newUser,
token,
message: 'Регистрация прошла успешно.',
})
} catch (error) {
res.json({ message: 'Ошибка при создании пользователя.' })
}
}

// Login user
export const login = async (req, res) => {
try {
const { username, password } = req.body
const user = await User.findOne({ username })

if (!user) {
return res.json({
message: 'Такого юзера не существует.',
})
}

const isPasswordCorrect = await bcrypt.compare(password, user.password)

if (!isPasswordCorrect) {
return res.json({
message: 'Неверный пароль.',
})
}

const token = jwt.sign(
{
id: user._id,
},
process.env.JWT_SECRET,
{ expiresIn: '30d' },
)

res.json({
token,
user,
message: 'Вы вошли в систему.',
})
} catch (error) {
res.json({ message: 'Ошибка при авторизации.' })
}
}

// Get Me
export const getMe = async (req, res) => {
try {
const user = await User.findById(req.userId)

if (!user) {
return res.json({
message: 'Такого юзера не существует.',
})
}

const token = jwt.sign(
{
id: user._id,
},
process.env.JWT_SECRET,
{ expiresIn: '30d' },
)

res.json({
user,
token,
})
} catch (error) {
res.json({ message: 'Нет доступа.' })
}
}
26 changes: 26 additions & 0 deletions controllers/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Comment from '../models/Comment.js'
import Post from '../models/Post.js'

export const createComment = async (req, res) => {
try {
const { postId, comment } = req.body

if (!comment)
return res.json({ message: 'Комментарий не может быть пустым' })

const newComment = new Comment({ comment })
await newComment.save()

try {
await Post.findByIdAndUpdate(postId, {
$push: { comments: newComment._id },
})
} catch (error) {
console.log(error)
}

res.json(newComment)
} catch (error) {
res.json({ message: 'Что-то пошло не так.' })
}
}
148 changes: 148 additions & 0 deletions controllers/posts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import Post from '../models/Post.js'
import User from '../models/User.js'
import Comment from '../models/Comment.js'
import path, { dirname } from 'path'
import { fileURLToPath } from 'url'

// Create Post
export const createPost = async (req, res) => {
try {
const { title, text } = req.body
const user = await User.findById(req.userId)

if (req.files) {
let fileName = Date.now().toString() + req.files.image.name
const __dirname = dirname(fileURLToPath(import.meta.url))
req.files.image.mv(path.join(__dirname, '..', 'uploads', fileName))

const newPostWithImage = new Post({
username: user.username,
title,
text,
imgUrl: fileName,
author: req.userId,
})

await newPostWithImage.save()
await User.findByIdAndUpdate(req.userId, {
$push: { posts: newPostWithImage },
})

return res.json(newPostWithImage)
}

const newPostWithoutImage = new Post({
username: user.username,
title,
text,
imgUrl: '',
author: req.userId,
})
await newPostWithoutImage.save()
await User.findByIdAndUpdate(req.userId, {
$push: { posts: newPostWithoutImage },
})
res.json(newPostWithoutImage)
} catch (error) {
res.json({ message: 'Что-то пошло не так.' })
}
}

// Get All Posts
export const getAll = async (req, res) => {
try {
const posts = await Post.find().sort('-createdAt')
const popularPosts = await Post.find().limit(5).sort('-views')

if (!posts) {
return res.json({ message: 'Постов нет' })
}

res.json({ posts, popularPosts })
} catch (error) {
res.json({ message: 'Что-то пошло не так.' })
}
}

// Get Post By Id
export const getById = async (req, res) => {
try {
const post = await Post.findByIdAndUpdate(req.params.id, {
$inc: { views: 1 },
})
res.json(post)
} catch (error) {
res.json({ message: 'Что-то пошло не так.' })
}
}

// Get All Posts
export const getMyPosts = async (req, res) => {
try {
const user = await User.findById(req.userId)
const list = await Promise.all(
user.posts.map((post) => {
return Post.findById(post._id)
}),
)

res.json(list)
} catch (error) {
res.json({ message: 'Что-то пошло не так.' })
}
}

// Remove post
export const removePost = async (req, res) => {
try {
const post = await Post.findByIdAndDelete(req.params.id)
if (!post) return res.json({ message: 'Такого поста не существует' })

await User.findByIdAndUpdate(req.userId, {
$pull: { posts: req.params.id },
})

res.json({ message: 'Пост был удален.' })
} catch (error) {
res.json({ message: 'Что-то пошло не так.' })
}
}

// Update post
export const updatePost = async (req, res) => {
try {
const { title, text, id } = req.body
const post = await Post.findById(id)

if (req.files) {
let fileName = Date.now().toString() + req.files.image.name
const __dirname = dirname(fileURLToPath(import.meta.url))
req.files.image.mv(path.join(__dirname, '..', 'uploads', fileName))
post.imgUrl = fileName || ''
}

post.title = title
post.text = text

await post.save()

res.json(post)
} catch (error) {
res.json({ message: 'Что-то пошло не так.' })
}
}

// Get Post Comments
export const getPostComments = async (req, res) => {
try {
const post = await Post.findById(req.params.id)
const list = await Promise.all(
post.comments.map((comment) => {
return Comment.findById(comment)
}),
)
res.json(list)
} catch (error) {
res.json({ message: 'Что-то пошло не так.' })
}
}
48 changes: 42 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,43 @@
const express = require('express')
import express from 'express'
import mongoose from 'mongoose'
import dotenv from 'dotenv'
import cors from 'cors'
import fileUpload from 'express-fileupload'

import authRoute from './routes/auth.js'
import postRoute from './routes/posts.js'
import commentRoute from './routes/comments.js'

const app = express()
app.all('/', (req, res) => {
console.log("Just got a request!")
res.send('Yo!')
})
app.listen(process.env.PORT || 3000)
dotenv.config()

// Constants
const PORT = process.env.PORT || 3001
const DB_USER = process.env.DB_USER
const DB_PASSWORD = process.env.DB_PASSWORD
const DB_NAME = process.env.DB_NAME

// Middleware
app.use(cors())
app.use(fileUpload())
app.use(express.json())
app.use(express.static('uploads'))

// Routes
// http://localhost:3002
app.use('/api/auth', authRoute)
app.use('/api/posts', postRoute)
app.use('/api/comments', commentRoute)

async function start() {
try {
await mongoose.connect(
`mongodb+srv://${DB_USER}:${DB_PASSWORD}@wabala.5pysdlx.mongodb.net/${DB_NAME}?retryWrites=true&w=majority`,
)

app.listen(PORT, () => console.log(`Server started on port: ${PORT}`))
} catch (error) {
console.log(error)
}
}
start()
10 changes: 10 additions & 0 deletions models/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import mongoose from 'mongoose'

const CommentSchema = new mongoose.Schema(
{
comment: { type: String, required: true },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
},
{ timestamps: true },
)
export default mongoose.model('Comment', CommentSchema)
15 changes: 15 additions & 0 deletions models/Post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import mongoose from 'mongoose'

const PostSchema = new mongoose.Schema(
{
username: { type: String },
title: { type: String, required: true },
text: { type: String, required: true },
imgUrl: { type: String, default: '' },
views: { type: Number, default: 0 },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
},
{ timestamps: true },
)
export default mongoose.model('Post', PostSchema)
24 changes: 24 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import mongoose from 'mongoose'

const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post',
},
],
},
{ timestamps: true },
)

export default mongoose.model('User', UserSchema)
1 change: 1 addition & 0 deletions node_modules/.bin/mime

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading