# All files / server/files add.js

23.53% Statements 8/34
0% Branches 0/16
0% Functions 0/8
25% Lines 8/32

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    691x
    1x
    1x
    1x
    1x
    1x
    1x

    1x

     import { expose } from 'postmsg-rpc'
    import { pre } from 'prepost'
    import pull from 'pull-stream'
    import PMS from 'pull-postmsg-stream'
    import shortid from 'shortid'
    import { isBufferJson, bufferFromJson } from '../../serialization/buffer'
    import { isFunctionJson, functionToJson } from '../../serialization/function'

    export default function (getIpfs, opts) {
      return {
        add: expose('ipfs.files.add', pre(
          (...args) => {
            const fileFromJsonOpts = { pms: opts }

            args[0] = Array.isArray(args[0])
              ? args[0].map(file => fileFromJson(file, fileFromJsonOpts))
              : fileFromJson(args[0], fileFromJsonOpts)

            return args
          },
          opts.pre('files.add'),
          (...args) => getIpfs().files.add(...args)
        ), opts),
        addPullStream: expose('ipfs.files.addPullStream', pre(
          opts.pre('files.addPullStream'),
          (...args) => {
            const readFnName = shortid()

            pull(
              PMS.source(args[0].name, opts),
              pull.map(obj => fileFromJson(obj, { pms: opts })),
              getIpfs().files.addPullStream(...args.slice(1)),
              PMS.sink(readFnName, opts)
            )

            return functionToJson(readFnName)
          }
        ), opts)
      }
    }

    function fileFromJson (obj, opts) {
      opts = opts || {}

      if (isBufferJson(obj)) { // Buffer
        return bufferFromJson(obj)
      } else if (isFunctionJson(obj)) { // Pull stream
        return pullStreamFromJson(obj, opts)
      } else if (obj && obj.content) { // Object { path?, content }
        return Object.assign({}, obj, { content: fileFromJson(obj.content, opts) })
      }

      return obj // Object { path } maybe, but could be anything
    }

    function pullStreamFromJson (obj, opts) {
      opts = opts || {}

      return PMS.source(obj.name, Object.assign({}, opts.pms, {
        post (res) {
          if (isBufferJson(res.data)) {
            res.data = bufferFromJson(res.data)
          }

          return res
        }
      }))
    }