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

Commit

Permalink
add http resource
Browse files Browse the repository at this point in the history
  • Loading branch information
nginnever committed Jun 15, 2016
1 parent 78653b3 commit e1ecd32
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/core/ipfs/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const isStream = require('isstream')
const promisify = require('promisify-es6')
const Duplex = require('stream').Duplex
const multihashes = require('multihashes')
const bs58 = require('bs58')

module.exports = function files (self) {
return {
Expand Down
67 changes: 67 additions & 0 deletions src/http-api/resources/files.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
'use strict'

const bs58 = require('bs58')
const multihash = require('multihashes')
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 +51,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 e1ecd32

Please sign in to comment.