{"size": 1568, "ext": "js", "max_stars_repo_path": "ipfsteleform/node_modules/ipfs-http-client/src/object/put.js", "max_stars_repo_name": "ap-aryanpandey/FlexiTestPort-", "max_stars_repo_stars_event_min_datetime": "2021-08-09T10:17:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:19:58.000Z", "max_issues_repo_path": "ipfsteleform/node_modules/ipfs-http-client/src/object/put.js", "max_issues_repo_name": "ap-aryanpandey/FlexiTestPort-", "max_issues_repo_issues_event_min_datetime": "2021-03-09T20:25:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T08:53:48.000Z", "max_forks_repo_path": "colony-starter/node_modules/ipfs-http-client/src/object/put.js", "max_forks_repo_name": "joeycharlesworth/Prediction_hubspot_colony", "max_forks_repo_forks_event_min_datetime": "2021-09-16T10:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:21:06.000Z"}
{"max_stars_count": 13, "max_issues_count": 9, "max_forks_count": 9, "avg_line_length": 21.1891891892, "max_line_length": 54, "alphanum_fraction": 0.53125}
'use strict'

const promisify = require('promisify-es6')
const CID = require('cids')
const { DAGNode } = require('ipld-dag-pb')

const SendOneFile = require('../utils/send-one-file')
const once = require('once')

module.exports = (send) => {
  const sendOneFile = SendOneFile(send, 'object/put')

  return promisify((obj, options, _callback) => {
    if (typeof options === 'function') {
      _callback = options
      options = {}
    }

    const callback = once(_callback)

    if (!options) {
      options = {}
    }

    let tmpObj = {
      Data: null,
      Links: []
    }

    if (Buffer.isBuffer(obj)) {
      if (!options.enc) {
        tmpObj = {
          Data: obj.toString(),
          Links: []
        }
      }
    } else if (DAGNode.isDAGNode(obj)) {
      tmpObj = {
        Data: obj.Data.toString(),
        Links: obj.Links.map(l => ({
          Name: l.Name,
          Hash: l.Hash.toString(),
          Size: l.Tsize
        }))
      }
    } else if (typeof obj === 'object') {
      tmpObj.Data = obj.Data.toString()
      tmpObj.Links = obj.Links
    } else {
      return callback(new Error('obj not recognized'))
    }

    let buf
    if (Buffer.isBuffer(obj) && options.enc) {
      buf = obj
    } else {
      buf = Buffer.from(JSON.stringify(tmpObj))
    }
    const enc = options.enc || 'json'

    const sendOptions = {
      qs: { inputenc: enc }
    }

    sendOneFile(buf, sendOptions, (err, result) => {
      if (err) {
        return callback(err) // early
      }

      callback(null, new CID(result.Hash))
    })
  })
}
