Skip to content

Commit

Permalink
feat(upload): Expanded IPFS Class for uploading files to the web
Browse files Browse the repository at this point in the history
  • Loading branch information
danielhumgon committed Jul 29, 2020
1 parent 18b8536 commit b12110a
Show file tree
Hide file tree
Showing 2 changed files with 433 additions and 16 deletions.
183 changes: 176 additions & 7 deletions src/ipfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ class IPFS {
}

/**
* @api IPFS.createFileModel() createFileModel() - Create a file model
* @apiName createFileModel()
* @api IPFS.createFileModelServer() createFileModelServer() - Create a file model
* @apiName createFileModelServer()
* @apiGroup IPFS
* @apiDescription Creates a new model on the server. If successful, will
* return an object with file data. That object contains a BCH address,
Expand All @@ -64,7 +64,7 @@ class IPFS {
* (async () => {
* try {
* const path = `${__dirname}/ipfs.js`
* let fileData = await bchjs.IPFS.uploadFile(path);
* let fileData = await bchjs.IPFS.createFileModelServer(path);
* console.log(fileData);
* } catch(error) {
* console.error(error)
Expand All @@ -90,7 +90,7 @@ class IPFS {
* "__v": 0
* }
*/
async createFileModel(path) {
async createFileModelServer(path) {
try {
// Ensure the file exists.
if (!_this.fs.existsSync(path))
Expand Down Expand Up @@ -131,7 +131,7 @@ class IPFS {
}

/**
* @api IPFS.uploadFile() uploadFile() - Upload a file to IPFS
* @api IPFS.uploadFileServer() uploadFileServer() - Upload a file to IPFS
* @apiName uploadFile()
* @apiGroup IPFS
* @apiDescription Upload a file to the FullStack.cash IPFS server. If
Expand All @@ -142,7 +142,7 @@ class IPFS {
* (async () => {
* try {
* const path = `${__dirname}/ipfs.js`
* let fileData = await bchjs.IPFS.uploadFile(path, "5ec562319bfacc745e8d8a52");
* let fileData = await bchjs.IPFS.uploadFileServer(path, "5ec562319bfacc745e8d8a52");
* console.log(fileData);
* } catch(error) {
* console.error(error)
Expand All @@ -157,7 +157,7 @@ class IPFS {
* "fileExtension": "js"
* }
*/
async uploadFile(path, modelId) {
async uploadFileServer(path, modelId) {
try {
// Ensure the file exists.
if (!_this.fs.existsSync(path))
Expand Down Expand Up @@ -270,6 +270,175 @@ class IPFS {
throw err
}
}
/**
* @api IPFS.createFileModelWeb() createFileModelWeb() - Create a file model
* @apiName createFileModelWeb()
* @apiGroup IPFS
* @apiDescription Creates a new model on the server. If successful, will
* return an object with file data. That object contains a BCH address,
* payment amount, and _id required to be able to upload a file.
*
* @apiExample Example usage:
* (async () => {
* try {
* const content = ['PSF']
* const name = 'psf.txt' // Content can be Array , ArrayBuffer , Blob
* const options = { type: "text/plain" }
* const file = new File(content,name,options)
* let fileData = await bchjs.IPFS.createFileModelWeb(file);
* console.log(fileData);
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* "success": true,
* "hostingCostBCH": 0.00004197,
* "hostingCostUSD": 0.01,
* "file": {
* "payloadLink": "",
* "hasBeenPaid": false,
* "_id": "5ec562319bfacc745e8d8a52",
* "schemaVersion": 1,
* "size": 4458,
* "fileName": "ipfs.js",
* "fileExtension": "js",
* "createdTimestamp": "1589994033.655",
* "hostingCost": 4196,
* "walletIndex": 49,
* "bchAddr": "bchtest:qzrpkevu7h2ayfa4rjx08r5elvpfu72dg567x3mh3c",
* "__v": 0
* }
*/
async createFileModelWeb(file) {
try {
if (!file) throw new Error(`File is required`)

const { name, size } = file

if (!name || typeof name !== "string")
throw new Error(`File should have the property 'name' of string type`)

if (!size || typeof size !== "number")
throw new Error(`File should have the property 'size' of number type`)

// Get the file extension.
const splitExt = name.split(".")
const fileExt = splitExt[splitExt.length - 1]

const fileObj = {
schemaVersion: 1,
size: size,
fileName: name,
fileExtension: fileExt
}
// console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)

const fileData = await _this.axios.post(`${this.IPFS_API}/files`, {
file: fileObj
})
// console.log(`fileData.data: ${JSON.stringify(fileData.data, null, 2)}`)

return fileData.data
} catch (err) {
console.error(`Error in createFileModelWeb()`)
throw err
}
}

/**
* @api IPFS.uploadFileWeb() uploadFileWeb() - Upload a file to IPFS
* @apiName uploadFileWeb()
* @apiGroup IPFS
* @apiDescription Upload a file to the FullStack.cash IPFS server. If
* successful, it will return an object with an ID, a BCH address, and an
* amount of BCH to pay.
*
* @apiExample Example usage:
* (async () => {
* try {
* * const content = ['PSF']
* const name = 'psf.txt' // Content can be Array , ArrayBuffer , Blob
* const options = { type: "text/plain" }
* const file = new File(content,name,options)
* let fileData = await bchjs.IPFS.uploadFile(file, "5ec562319bfacc745e8d8a52");
* console.log(fileData);
* } catch(error) {
* console.error(error)
* }
* })()
*
* {
* "schemaVersion": 1,
* "size": 2374,
* "fileId": "5ec562319bfacc745e8d8a52",
* "fileName": "ipfs.js",
* "fileExtension": "js"
* }
*/
async uploadFileWeb(file, modelId) {
try {
if (!file) throw new Error(`File is required`)

const { name, type, size } = file

if (!name || typeof name !== "string")
throw new Error(`File should have the property 'name' of string type`)

if (!type || typeof type !== "string")
throw new Error(`File should have the property 'type' of string type`)

if (!size || typeof size !== "number")
throw new Error(`File should have the property 'size' of number type`)

if (!modelId) {
throw new Error(
`Must include a file model ID in order to upload a file.`
)
}

// Prepare the upload object. Get a file ID from Uppy.
const id = _this.uppy.addFile({
name: name,
data: file,
source: "Local",
isRemote: false
})
// console.log(`id: ${JSON.stringify(id, null, 2)}`)

// Add the model ID, required to be allowed to upload the file.
_this.uppy.setFileMeta(id, { fileModelId: modelId })

// Upload the file to the server.
const upData = await _this.uppy.upload()

if (upData.failed.length)
throw new Error("The file could not be uploaded")

if (upData.successful.length) {
delete upData.successful[0].data
// console.log(`upData: ${JSON.stringify(upData, null, 2)}`)

const fileObj = {
schemaVersion: 1,
size: upData.successful[0].progress.bytesTotal,
fileId: upData.successful[0].meta.fileModelId,
fileName: upData.successful[0].name,
fileExtension: upData.successful[0].extension
}
// console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)

return fileObj
// return true
}

return false
} catch (err) {
console.error(`Error in bch-js/src/ipfs.js/uploadFileWeb(): `)
throw err
}
}
}

module.exports = IPFS
Loading

0 comments on commit b12110a

Please sign in to comment.