Skip to content

Commit

Permalink
Partially check file size (#3)
Browse files Browse the repository at this point in the history
We need to totally abort the request when the file is too big.
Right now, the server detects that case but it still uploads the file.
  • Loading branch information
francoischalifour committed Mar 5, 2017
1 parent 54aca77 commit 4f35b0d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
12 changes: 10 additions & 2 deletions api/v1/classify/Classify.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const { APIError } = require('../../../helpers/error')
const { createError } = require('../../../helpers/response')
const { logger, modelDirectory, pythonPath } = require('../../../config')

const BIT_TO_BYTES = 1048576
const MAX_FILE_SIZE = 10 * BIT_TO_BYTES
const AUTHORIZED_FORMATS = ['jpg', 'jpeg']

module.exports = dependencies => {
Expand All @@ -26,12 +28,19 @@ module.exports = dependencies => {

return {
* classify ({ request, response }) {
const { parts, contentLength } = request
const { answer, abort } = response
const { parts } = request

let filepath

try {
if (contentLength > MAX_FILE_SIZE) {
const code = 413
const message = `The file is too big (maximum size allowed is ${MAX_FILE_SIZE / BIT_TO_BYTES} MB).`

throw new APIError({ code, message })
}

const part = yield parts

if (!part) {
Expand All @@ -42,7 +51,6 @@ module.exports = dependencies => {
}

const { mime } = part

const [, format] = mime.split('/')

if (!AUTHORIZED_FORMATS.includes(format)) {
Expand Down
4 changes: 3 additions & 1 deletion api/v1/classify/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ const Controller = require('./Classify.controller')({
router
.post('/', function * (next) {
const parts = parse(this)
const contentLength = this.request.header['content-length']

yield Controller.classify({
request: {
parts
parts,
contentLength
},
response: {
answer: data => (this.body = data),
Expand Down

0 comments on commit 4f35b0d

Please sign in to comment.