首页 > 解决方案 > 编写多步发布路线的最有效方法是什么?NodeJS、Express、Mongo、IPFS

问题描述

我正在做一个项目,我的帖子路线基本上是这样写的:

router.post('/', async(req, res) => {
    if (req.session.loggedIn && req.files) {
//append user entered name to reflect appropriate file extension
        let ext = path.extname(req.files.file.name)
        req.files.file.name = req.body.filename + ext;

// Take all the req data and declare for later use
        const file = req.files.file
        const fileName = file.name;
        const authKey = req.session.authKey;
        const content = req.body.content
        const fileTags = req.body.tags;
        const filePath = '/tmp/' + fileName;

//Copy file from req to the server into 'uploads' folder     
        file.mv('./uploads/' + fileName, function(err) {
            if (err) { throw err; }
            return emitter.emit('moved')
        })

        let baseFile = path.join('./uploads', path.basename(filePath));
        console.log(`BASEFILE: ${baseFile}`)
//Encrypt File from 'uploads' (the encrypt function outputs to 'tmp' directory on server
        emitter.on('moved', async function() {
                console.log(`File has been moved, Encrypting ${baseFile} now.`)
                await encrypt({ file: baseFile, password: authKey })
                return emitter.emit('encrypted')
            })
//Erase upload file from server
        emitter.on('Yoo Hoo Clean Up!!', function() {
            console.log('Erasing Base File')
            cleanUp(baseFile)
            emitter.emit('respond')
        })

// Add Pertinent info to MongoDB for retrieving the file later
        emitter.on('ipfs-complete', async function dbWriteFile(fileHash) {
            console.log('Adding to Database')
            await db.IPFS.create({ owner: db.User._id, title: fileName, content: content, dbCID: fileHash, tags: fileTags })
                .then((file) => {
                    console.log(`New IPFS FILE: ${file}`);
                    emitter.emit('Yoo Hoo Clean Up!!')

                })
        })

//Add File to IPFS remote Node and return the hash of the file
        emitter.on('encrypted', async function() {
            console.log('Adding to IPFS')
            let tmpFile = `${fileName}.enc`
            let tmpPath = path.join('./tmp/', tmpFile)
            console.log(`tmpFile: ${tmpFile}`)
            console.log(`tmpPath PARSE: ${tmpPath}`)
            const fileHash = await addFile(`./${tmpFile}`, tmpPath)
            return emitter.emit('ipfs-complete', fileHash)

        })


        emitter.on('respond', function() {
            res.redirect('/recap')
        })
    } else {
        res.status(404).json({ message: `Bad Request received check your request again, bruh.` })
    }
})

需要注意的几点:

  1. 每个函数(移动文件、加密文件、添加到 IPFS、写入数据库)在单独执行时都可以完美运行,但是当我尝试将它们一起运行时,上传到 IPFS 的“文件”总是返回 6 字节大小的相同哈希。

  2. 发射器事件是我最近尝试强制执行命令(非常不成功)2a。我为我的代码绝对是垃圾而道歉,但我已经为此工作了几天并且有点放弃保持它的漂亮,但是一旦我弄清楚了这一点,我会重构和美化它。

3.我对编码还很陌生,所以这可能(而且可能是)一些愚蠢的事情。我承认这一点,并非常感谢我能得到的任何帮助。

  1. 如果有人愿意帮助我,但需要更多代码(即 addFile() 或 encrypt() 的样子),我非常乐意分享更多。

提前感谢您的任何和所有建议/指示/批评。

标签: node.jsmongodbipfs

解决方案


对于任何在同一问题上苦苦挣扎的人,基本上我需要调用addFile()作为回调encrypt()并传入writestream.path作为参数。


推荐阅读