0.0.1-0 • Published 5 years ago

sine-busboy v0.0.1-0

Weekly downloads
-
License
ISC
Repository
bitbucket
Last release
5 years ago

Busboy middleware

Installation

npm i --save @sine/sine-busboy

Usage

The busboy middleware can be used on any express router

router.post(
  '/test-file',
  busboyMiddleware(controllerFn, { maxBytes: 1000 }),
);

The middleware wraps the controller function and adds a file to the request object. The format of the file is

{
  fieldName: string;
  name: string;
  mimeType: string;
  encoding: string;
  stream: NodeJS.ReadableStream;
}

A response from the controller function in following form is expected

{
  status: number;
  json: any;
}

Example controller

The following code snippet is an example of the input/return types required by the busboy middleware

async uploadImage(sc, req) {
  const { file: { stream, name } } = req;

  await fileService.uploadImage(sc, name, stream);

  return {
    status: 202
  };
}

Configuration

There are options that can be set on the busboy middleware to restrict file size and type

  • maxBytes - the maximum size (in bytes) that should be accepted
  • allowedMimeTypes - an optional array of allowed mime types, ie. 'text/csv', 'image/png'

Error handling

By default the busboyMiddleware throws three different errors:

  • TooManyFiles
  • FileTooLarge
  • InvalidFileType

These can either be handled in a diy error handler or the provided busboyErrorHandler can be used to map them to status codes

router.post(
  '/test-file',
  busboyMiddleware(controllerFn, { maxBytes: 1000 }),
  busboyErrorHandler({ maxBytes: 1000 }),
);

The status codes that are expected using the error handler are:

  • 413 - MAX_REQUEST_SIZE_EXCEEDED
  • 400 - INVALID_FILE_TYPE
  • 400 - TOO_MANY_FILES
0.0.1-0

5 years ago