generated from Ragtulf/express-api-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
206 lines (185 loc) · 5.5 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import express from 'express'
import bodyParser from 'body-parser'
import dotenv from 'dotenv'
import cloudinaryFramework from 'cloudinary'
import multer from 'multer'
import cloudinaryStorage from 'multer-storage-cloudinary'
import cors from 'cors'
import mongoose from 'mongoose'
import bcrypt from 'bcrypt-nodejs'
import { Recipe } from './models/food'
import { User } from './models/users'
dotenv.config()
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/food-app"
mongoose.connect(mongoUrl,
{ useNewUrlParser: true,
useUnifiedTopology: true })
mongoose.Promise = Promise
// Cloudinary to store images
const cloudinary = cloudinaryFramework.v2;
cloudinary.config({
cloud_name: 'dnqxxs1yn',
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
})
const storage = cloudinaryStorage({
cloudinary,
params: {
folder: 'recipeImages',
allowedFormats: ['jpg', 'png'],
transformation: [{ width: 500, height: 500, crop: 'limit' }],
},
})
const parser = multer({ storage })
// Authentication for users
const authenticateUser = async (req, res, next) => {
const user = await User.findOne({ accessToken: req.header('Authorization')})
if (user) {
req.user = user
next()
} else {
res.status(403).json({ message: 'Access forbidden!' })
}
}
// Port
const port = process.env.PORT || 8080
const app = express()
// Middleware
app.use(cors())
app.use(bodyParser.json())
// Routes
app.get('/', (req, res) => {
res.send('Our pretty Food App! 🍌')
})
// Signup
app.post('/signup', async (req, res) => {
try {
const { userName, email, password, shortBio } = req.body
const avatar = Math.floor(Math.random() * 16) +1
const user = new User({ userName, avatar, email, password: bcrypt.hashSync(password), shortBio })
const savedUser = await user.save()
res.status(201).json({ id: savedUser._id, acesssToken: savedUser.accessToken })
} catch (err) {
res.status(400).json({ message: 'Could not create user', err: err.errors })
}
})
// Login
app.post('/login', async (req, res) => {
const user = await User.findOne({ userName: req.body.userName })
if (user && bcrypt.compareSync(req.body.password, user.password)) {
res.json({ userID: user._id, accessToken: user.accessToken })
} else {
res.status(400).json({ message: 'Could not find user' })
}
})
// A specific user profile page
app.get('/login/user/:id', async (req, res) => {
const {id} = req.params
try {
const user = await User.findById(id)
res.status(201).json(user)
} catch (err) {
res.status(400).json({ message: 'No user found.'})
}
})
// Finds all recipes by specific user
app.get('/users/:id/recipes', async (req, res) => {
const { id } = req.params
try {
const userRecipes = await Recipe.find({ createdBy: id})
res.json(userRecipes)
} catch (err) {
res.status(400).json({ message: 'Does not work at all!'})
}
})
// Add profile pic to user model
app.post('/login/user/:id/image', parser.single('image'), async (req, res) => {
const { id } = req.params
try {
const userProfile = await User.findOneAndUpdate(
{ _id: id },
{ profilePic: req.file.path, profilePicName: req.file.filename },
{ new: true })
res.json(userProfile)
} catch (err) {
res.status(400).json({ message: "Can't post profile pic" })
}
})
// Create recipe (needs authentication)
app.post('/recipes', authenticateUser)
app.post('/recipes', async (req, res) => {
try {
const { title, shortDescription, ingredients, directions, tags } = req.body
const recipe = await new Recipe({
title,
shortDescription,
ingredients,
directions,
tags,
createdBy: req.user._id
}).save()
res.status(201).json(recipe)
} catch (err) {
console.log(JSON.stringify(err))
res.status(400).json({ message: 'Did not work!', error: err.errors })
}
})
// Lists recipes for feed
app.get('/recipes', async (req, res) => {
try {
const recipes = await Recipe.find().populate({
path: 'createdBy',
select: ['userName', 'profilePic', 'avatar']
}).sort({ createdAt:'desc' }).exec()
res.json(recipes)
} catch (err) {
res.status(400).json({ message: "Not working!" })
}
})
// Lists recipes by tag search
app.get('/recipes/tags/:tag', async (req, res) => {
const { tag } = req.params
try {
const findTags = await Recipe.find({tags: { $regex: new RegExp(tag, 'i')}})
.populate({
path: 'createdBy',
select: ['userName', 'profilePic', 'avatar']
})
if (findTags.length > 0) {
res.json(findTags)
} else {
res.status(400).json({ message: 'Not working'})
}
} catch (err) {
res.status(400).json({ message: 'No tags'})
}
})
// GET a specific recipe
app.get('/recipes/:id', async (req, res) => {
const { id } = req.params
try {
const recipe = await Recipe.findById(id).populate({
path: 'createdBy',
select: ['userName', 'profilePic', 'avatar']
})
res.json(recipe)
} catch (err) {
res.status(400).json({ message: 'Does not work!'})
}
})
// Add image to a specific recipe
app.post('/recipes/:id/image', parser.single('image'), async (req, res) => {
const { id } = req.params
try {
const updatedRecipe = await Recipe.findOneAndUpdate(
{ _id: id },
{ imageUrl: req.file.path, imageName: req.file.filename },
{ new: true })
res.json(updatedRecipe)
} catch (err) {
res.status(400).json({ message: "Can't post image" })
}
})
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})