Skip to content
This repository has been archived by the owner on Feb 12, 2024. It is now read-only.

Commit

Permalink
feat(add): add the http endpoint for files.add
Browse files Browse the repository at this point in the history
  • Loading branch information
nginnever authored and daviddias committed Sep 12, 2016
1 parent 2bf49ea commit e29f429
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 1 deletion.
1 change: 0 additions & 1 deletion src/core/ipfs/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ module.exports = function object (self) {
if (err) {
return cb(err)
}

cb(null, node.data)
})
}),
Expand Down
66 changes: 66 additions & 0 deletions src/http-api/resources/files.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict'

const bs58 = require('bs58')
const ndjson = require('ndjson')
const multipart = require('ipfs-multipart')
const debug = require('debug')
const log = debug('http-api:files')
log.error = debug('http-api:files:error')
Expand Down Expand Up @@ -48,3 +50,67 @@ exports.cat = {
})
}
}

exports.add = {
handler: (request, reply) => {
if (!request.payload) {
return reply('Array, Buffer, or String is required.').code(400).takeover()
}

const parser = multipart.reqParser(request.payload)

var filesParsed = false
var filesAdded = 0

var serialize = ndjson.serialize()
// hapi doesn't permit object streams: http://hapijs.com/api#replyerr-result
serialize._readableState.objectMode = false

request.server.app.ipfs.files.createAddStream((err, fileAdder) => {
if (err) {
return reply({
Message: err,
Code: 0
}).code(500)
}

fileAdder.on('data', (file) => {
serialize.write({
Name: file.path,
Hash: bs58.encode(file.node.multihash()).toString()
})
filesAdded++
})

fileAdder.on('end', () => {
if (filesAdded === 0 && filesParsed) {
return reply({
Message: 'Failed to add files.',
Code: 0
}).code(500)
} else {
serialize.end()
return reply(serialize)
.header('x-chunked-output', '1')
.header('content-type', 'application/json')
}
})

parser.on('file', (fileName, fileStream) => {
var filePair = {
path: fileName,
content: fileStream
}
filesParsed = true
fileAdder.write(filePair)
})

parser.on('end', () => {
if (!filesParsed) {
return reply("File argument 'data' is required.").code(400).takeover()
}
fileAdder.end()
})
})
}
}
12 changes: 12 additions & 0 deletions src/http-api/routes/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,16 @@ module.exports = (server) => {
handler: resources.files.cat.handler
}
})

api.route({
method: '*',
path: '/api/v0/add',
config: {
payload: {
parse: false,
output: 'stream'
},
handler: resources.files.add.handler
}
})
}

0 comments on commit e29f429

Please sign in to comment.