diff --git a/examples/upload.html b/examples/upload.html index 7c8bc6d..9d218b9 100644 --- a/examples/upload.html +++ b/examples/upload.html @@ -4,17 +4,11 @@ - Upload to IPFS - - - - -
-
+
@@ -24,11 +18,27 @@
-
- - - +
+ + Pin + +
+ +
+ +
+ + Unpin + +
+ +
+ diff --git a/models/ipfs.js b/models/ipfs.js index e2653f8..9408624 100644 --- a/models/ipfs.js +++ b/models/ipfs.js @@ -7,6 +7,7 @@ const { ObjectId } = require('mongodb'); const collectionName = 'ipfs'; exports.create = create; +exports.update = update; exports.findOne = findOne; async function create(params) { diff --git a/package.json b/package.json index cfb731d..3fd8bf2 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "start": "node ./bin/www" }, "dependencies": { + "cids": "^1.1.9", "cookie-parser": "~1.4.4", "crypto-js": "^4.0.0", "dotenv": "^16.0.3", diff --git a/routes/index.js b/routes/index.js index fdba91c..23b2bbe 100644 --- a/routes/index.js +++ b/routes/index.js @@ -1,5 +1,6 @@ "use strict"; +const CID = require('cids'); const fs = require('node:fs').promises; const path = require('node:path'); const createError = require('http-errors'); @@ -106,4 +107,65 @@ async function handleIpfs(bitmap, options) { return uploaded; } +router.all("/pin/:cid", async function (req, res, next) { + pinOrUnpin(req.params.cid, true).then(() => { + res.json({ + success: true, + message: 'OK' + }); + }).catch(next); +}); + +router.all("/unpin/:cid", async function (req, res, next) { + pinOrUnpin(req.params.cid, false).then(() => { + res.json({ + success: true, + message: 'OK' + }); + }).catch(next); +}); + +async function pinOrUnpin(cid, pin) { + if (!cid || pin === undefined) { + throw new Error("Insufficient parameter received."); + } + + if (!cid) { + throw new Error("Expecting CID."); + } + + if (typeof pin !== 'boolean') { + throw new Error("Expecting pin to be a boolean value."); + } + + const cidInstance = new CID(cid); + + if (!CID.isCID(cidInstance)) { + throw new Error(`${cid} is an invalid CID.`); + } + + if (pin === true) { + await ipfs.pin(cid); + } else { + await ipfs.unpin(cid); + } + + let existInLog = await ipfsModel.findOne({ path: cid }); + + if (existInLog && existInLog._id) { + await ipfsModel.update({ + _id: existInLog._id, + pin: pin + }); + } else { + await ipfsModel.create({ + name: '', + size: 0, + type: '', + path: cid, + pin: pin + }); + } +} + module.exports = router;