3 var uuid = require('node-uuid')
4 , CombinedStream = require('combined-stream')
5 , isstream = require('isstream')
8 function Multipart (request) {
10 this.boundary = uuid()
15 Multipart.prototype.isChunked = function (options) {
18 , parts = options.data || options
21 self.request.emit('error', new Error('Argument error, options.multipart.'))
24 if (options.chunked !== undefined) {
25 chunked = options.chunked
28 if (self.request.getHeader('transfer-encoding') === 'chunked') {
33 parts.forEach(function (part) {
34 if (typeof part.body === 'undefined') {
35 self.request.emit('error', new Error('Body attribute missing in multipart.'))
37 if (isstream(part.body)) {
46 Multipart.prototype.setHeaders = function (chunked) {
49 if (chunked && !self.request.hasHeader('transfer-encoding')) {
50 self.request.setHeader('transfer-encoding', 'chunked')
53 var header = self.request.getHeader('content-type')
55 if (!header || header.indexOf('multipart') === -1) {
56 self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
58 if (header.indexOf('boundary') !== -1) {
59 self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
61 self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
66 Multipart.prototype.build = function (parts, chunked) {
68 var body = chunked ? new CombinedStream() : []
71 if (typeof part === 'number') {
72 part = part.toString()
74 return chunked ? body.append(part) : body.push(new Buffer(part))
77 if (self.request.preambleCRLF) {
81 parts.forEach(function (part) {
82 var preamble = '--' + self.boundary + '\r\n'
83 Object.keys(part).forEach(function (key) {
84 if (key === 'body') { return }
85 preamble += key + ': ' + part[key] + '\r\n'
92 add('--' + self.boundary + '--')
94 if (self.request.postambleCRLF) {
101 Multipart.prototype.onRequest = function (options) {
104 var chunked = self.isChunked(options)
105 , parts = options.data || options
107 self.setHeaders(chunked)
108 self.chunked = chunked
109 self.body = self.build(parts, chunked)
112 exports.Multipart = Multipart