Skip to content

Commit

Permalink
updatea server
Browse files Browse the repository at this point in the history
  • Loading branch information
EhsanParsania committed Jun 5, 2021
1 parent 2dace1b commit 27c6d97
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 21 deletions.
42 changes: 28 additions & 14 deletions db.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
{
"products": [
"posts": [
{
"name": "asus laptop",
"brand": "asus",
"image": "/files/3d545729eb7cdb3f85407805ec160740",
"price": "1000",
"createdAt": 1622901942857,
"id": 1
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"orders": [
{
"user": "Mona",
"id": 1,
"price": "320$",
"quantity": 123
},
{
"name": "apple laptop",
"brand": "apple",
"image": "/files/65ddd8b1bbce4d8396b62611147fa1d6",
"price": "2000",
"createdAt": 1622901942857,
"user": "Mandy",
"price": "100$",
"quantity": 67,
"id": 2
}
,
},
{
"user": "Morgan",
"price": "150$",
Expand Down Expand Up @@ -102,6 +104,14 @@
"price": "120$",
"color": "black",
"id": 6
},
{
"createdAt": 1622911000600,
"id": 7
},
{
"createdAt": 1622911041032,
"id": 8
}
],
"customers": [
Expand Down Expand Up @@ -202,6 +212,10 @@
"gender": "m",
"createdAt": 1622905751655,
"id": 14
},
{
"createdAt": 1622911074310,
"id": 15
}
]
}
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
"version": "1.0.0",
"description": "Backend project for a frontend exercise for Maktab47 bootcamp, with json-server and file upload",
"main": "index.js",

"backend:dev": "nodemon server"
"backend:dev": "nodemon server",
"author": "Babak Khorrami",
"license": "MIT",
"dependencies": {
Expand Down Expand Up @@ -48,4 +47,4 @@
"multer": "^1.4.2",
"nodemon": "^2.0.7"
}
}
}
44 changes: 40 additions & 4 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
const fs = require('fs')
const path = require('path')
const multer = require('multer')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })

// Set default middlewares (logger, static, cors and no-cache)
Expand All @@ -29,13 +29,48 @@ server.get('/files', (req, res, next) => {
server.get('/files/:file_id', (req, res, next) => {
const { file_id } = req.params
res.set('Content-Type', 'image/jpeg')
res.sendFile(path.join(__dirname, 'uploads/' + file_id))
res.sendFile(path.join(__dirname, 'uploads/'+file_id))
})

// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser)


// For all non-json POST requests (object creation endpoints using an image file)
// 1- Upload the file inside the `image` field
// 2- (do it in next middleware)
const imageFieldUploadMiddleware = upload.single('image')
server.use((req, res, next) => {
if (req.method === 'POST' && req.headers['content-type'] != 'application/json') {
imageFieldUploadMiddleware(req, res, next)
} else {
next()
}
})

// If previous middle-ware worked, continue to next step
// 1- (previous middle-ware already did first step)
// 2- Validate uploaded file, and replace the `image` field value with the file path
server.use((req, res, next) => {
// if there was a file uploaded and previous middleware worked:
// req.file is the `image` file
// req.body will hold the text fields, if there were any
if (req.file) {
const { mimetype, size, filename } = req.file

// validate uploaded image
if (mimetype != 'image/jpeg') throw new Error('image should be in image/jpeg type')
if (size > 2*1024*1024) throw new Error('image size should be less than 2MB')

// Replace image field value with the file's path
req.body.image = '/files/'+filename
}
// continue to normal json-server router for actual creation
next()
})


// Add createdAt field with timestamp value when posting to any route
server.use((req, res, next) => {
if (req.method === 'POST') {
Expand All @@ -47,6 +82,7 @@ server.use((req, res, next) => {

// Use default router (CRUDs of db.json)
server.use(router)

server.listen(3001, () => {
console.log('JSON Server is running on http://localhost:3001')
})
console.log('Customized JSON-Server is running at http://localhost:3001/')
})

0 comments on commit 27c6d97

Please sign in to comment.