How to access my IPFS node instance from my express router

295 Views Asked by At

I can't seem to work out the correct approach for running a IPFS node in my express app (/services/IPFS.js), while also being able to access it within my routes (/routes/uploads.js)

/services/IPFS.js

const IPFS = require("ipfs-core");

module.exports = startNode = async (req, res, next) => {
  console.log("Starting IPFS node...");
  return await IPFS.create();
};

index.js

const express = require("express");
const bodyParser = require("body-parser");
const apiRouter = require("./routes/api");
const cors = require("cors");
const app = express();
const port = 4000;
const startNode = require("./services/IPFS");

app.use(cors());

app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

app.use("/api/v1", apiRouter);

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

startNode();

How do I pass my IPFS instance through to /routes/upload.js so I can use ipfs.add(file) in my /upload endpoint?

Any help appreciated.

Thanks

1

There are 1 best solutions below

1
On

You could define the apiRouter as a factory function and pass the startNode function to it. In your router you can then call it:

// in your index.js
// ...
app.use("/api/v1", apiRouter(startNode));
// ...

// in your apiRouter.js
const express = require('express');
const router = express.Router();

module.exports = (startNodeFn) => {

    router.post('/upload', async (req, res) => {
       const result = await startNodeFn.call(startNodeFn, req, res);
       // handle result and do upload ...
    });

    // rest of routes
    // ...
    return router;
}