Skip to content

Commit 16dcc27

Browse files
authored
Merge pull request #3 from vibhasfl/feature/adding-fileupload
Added fileupload using multer
2 parents ecbbc71 + 650f913 commit 16dcc27

File tree

8 files changed

+44
-6
lines changed

8 files changed

+44
-6
lines changed

.env.sample

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ MYSQL_USERNAME='root'
1212
MYSQL_PASSWORD='root'
1313
MYSQL_DATABASE='testdb'
1414
USE_MONGODB='true'
15-
USE_MYSQL='true'
15+
USE_MYSQL='true'
16+
FILE_UPLOAD_SIZE_IN_BYTES=1000000

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ Nodejs boilerplate with express,Mongoose,Mysql,JWT,ES6,ES7,ES8 support to develo
2626
- Manage enviroment via [dotenv](https://github.com/rolodato/dotenv-safe)
2727
- Code coverage with [istanbul](https://github.com/istanbuljs/nyc)
2828
- uses [helmet](https://github.com/helmetjs/helmet) to secure api endpoints which adds necessary security headers
29-
- Added support for databases like [mysql](https://github.com/mysqljs/mysql) and [mongoDB](https://github.com/Automattic/mongoose) with async await
29+
- Added support for databases like [mysql](https://github.com/mysqljs/mysql) and [mongoDB](https://github.com/Automattic/mongoose) with
30+
async await
31+
- Fileupload using [multer](https://github.com/expressjs/multer)
3032
## Getting Started
3133
1. Clone repository
3234
```

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"joi": "^14.3.1",
1616
"jsonwebtoken": "^8.4.0",
1717
"mongoose": "^5.4.10",
18+
"multer": "^1.4.1",
1819
"mysql": "^2.16.0"
1920
},
2021
"devDependencies": {

server/app.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const app = express()
1414

1515
app.use(bodyParser.json())
1616
app.use(helmet())
17-
app.use(jwt({ secret: secretCallback }).unless({ path: [ '/api/health-check', '/api/users', '/api/auth/login', '/api/users/testmysqlroute' ], requestProperty: 'auth' }))
17+
app.use(jwt({ secret: secretCallback }).unless({ path: [ '/api/health-check', '/api/users', '/api/auth/login', '/api/users/testmysqlroute', '/api/fileupload' ], requestProperty: 'auth' }))
1818
app.use('/api', Router)
1919

2020
// Handle 404

server/config/errorHandler.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { httpStatus } from '../utils/httpStatus'
22
import debug from 'debug'
3-
import { AppError } from '../utils/appError'
43

54
const log = debug('app')
65

@@ -10,7 +9,7 @@ const log = debug('app')
109
const errorHandler = (err, req, res, next) => {
1110
log(err.toString())
1211

13-
if (err instanceof AppError) return res.status(err.status).json({ error: err.message, stack: process.env.APP_ENVIROMENT === 'dev' ? err.stack : undefined })
12+
if (err.name === 'AppError') return res.status(err.status).json({ error: err.message, stack: process.env.APP_ENVIROMENT === 'dev' ? err.stack : undefined })
1413

1514
if (err.name === 'UnauthorizedError') return res.status(httpStatus.UNAUTHORIZED).json({ error: err.message })
1615

server/config/routes.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
import express from 'express'
22
import { userRoutes } from '../modules/users/user.routes'
33
import { authRoutes } from '../modules/auth/auth.routes'
4+
import { upload } from '../utils/upload'
5+
import { httpStatus } from '../utils/httpStatus'
46
const Router = express.Router()
57

68
Router.all('/health-check', (req, res) => res.json({ message: 'OK' }))
79
Router.use('/users', userRoutes)
810
Router.use('/auth', authRoutes)
911

12+
Router.post('/fileupload', upload.single('avatar'), (req, res) => {
13+
if (!req.file) return res.status(httpStatus.UNPROCESSABLE_ENTITY).json({ error: 'Please select file' })
14+
return res.json({ data: req.file })
15+
})
16+
1017
export { Router }

server/utils/appError.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@ export class AppError extends Error {
22
constructor (message, status) {
33
super(message)
44
this.status = status
5-
Error.captureStackTrace(this, AppError)
5+
this.name = 'AppError'
66
}
77
}

server/utils/upload.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import multer from 'multer'
2+
import crypto from 'crypto'
3+
import { AppError } from './appError'
4+
import { httpStatus } from './httpStatus'
5+
6+
// Ref : https://www.npmjs.com/package/multer
7+
8+
const storage = multer.diskStorage({
9+
// Note : You can set your own upload path Ref : https://www.npmjs.com/package/multer#diskstorage
10+
// destination: function (req, file, cb) {},
11+
filename: function (req, file, cb) {
12+
crypto.randomBytes(16, function (err, raw) {
13+
if (err) cb(err)
14+
cb(null, raw.toString('hex') + Date.now() + '.' + file.originalname.split('.').pop().trim())
15+
})
16+
}
17+
})
18+
19+
const limits = { fileSize: parseInt(process.env.FILE_UPLOAD_SIZE_IN_BYTES) || 1000000 }
20+
21+
const fileFilter = function (req, file, cb) {
22+
if (![ 'image/png', 'image/jpg', 'image/jpeg' ].includes(file.mimetype)) {
23+
return cb(new AppError('Only jpg,jpeg,png formats are allowed', httpStatus.UNPROCESSABLE_ENTITY))
24+
}
25+
cb(null, true)
26+
}
27+
28+
export const upload = multer({ storage, limits, fileFilter })

0 commit comments

Comments
 (0)