Arrow keys: ← previous · → next 33 of 37
@nodedk/upload
0.1.0 stable server

upload#

Stream raw file uploads to a destination callback. No multipart parsing, provider dependencies, or whole-file buffering.

Usage#

The factory returns an upload(req, handler) function. In @nodedk/server, register it under plugins and call it from begin:

var upload = require('@nodedk/upload')
var sanity = require('@nodedk/sanity')({
  clientOptions: {
    projectId: process.env.SANITY_PROJECT_ID,
    dataset: 'production',
    token: process.env.SANITY_TOKEN
  }
}).client

module.exports = {
  plugins: {
    upload: upload({ limit: 1000000 })
  },

  async begin(state) {
    if (state.req.pathname !== '/upload') return
    if (state.req.method !== 'POST') {
      state.res.statusCode = 405
      return null
    }

    // Authenticate here before starting the upload.
    try {
      return await state.plugins.upload(state.req, async function (stream) {
        return sanity.upload('file', stream, {
          filename: state.req.query.filename,
          contentType: state.req.headers['content-type']
        })
      })
    } catch (err) {
      state.res.shouldKeepAlive = false
      state.res.statusCode = 500
      return { ok: false, message: err.message }
    }
  }
}

sanity above is your configured Sanity client. The callback can instead forward to a configured S3 client:

return storage.stream({
  key: 'uploads/document.pdf',
  body: stream,
  size: Number(state.req.headers['content-length']),
  type: state.req.headers['content-type']
})

S3's stream() requires a known size. Require Content-Length for that endpoint; requests without it are supported by the uploader but cannot use this S3 method. The application selects the destination and handles provider error results, including Sanity's { ok: false } responses.

API#

upload(config)#

Creates an uploader. limit defaults to 1,000,000 bytes.

upload(req, handler)#

Accepts a Node HTTP request and calls handler(stream) with a bounded readable stream. The callback must consume the stream and await the destination upload. Its result is returned; undefined becomes null to finish a server begin hook without falling through to routing.

Declared oversized bodies are rejected before the callback runs. Actual bytes are counted too, including chunked requests. Errors use plain Error objects:

  • Upload too large: the declared or received size exceeds the limit.
  • Upload incomplete: the received size differs from Content-Length.
  • Upload aborted: the client aborts the request.
  • Upload not consumed: the callback returns before consuming the stream.

Request and destination errors also reject the call. Errors have no custom status codes; the caller decides how to respond.

Backpressure follows the destination's consumption. On failure, the uploader unpipes and pauses the request and destroys the destination stream. The caller owns the HTTP response and should close the connection when rejecting an unread body. A callback returning before consuming the stream is an error. Routing, methods, authentication, and request timeouts belong to the application.

Development#

npm test

Tests use local HTTP requests and streams; no provider credentials are needed.

Created by Vidar Eldøy

Tools for business systems.