Как получить доступ к моему экземпляру узла IPFS с моего экспресс-маршрутизатора

Кажется, я не могу найти правильный подход для запуска узла IPFS в моем экспресс-приложении (/services/IPFS.js), а также могу получить к нему доступ в моих маршрутах (/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();

Как передать свой экземпляр IPFS на /routes/upload.js, чтобы я мог использовать ipfs.add(file) в своей /upload конечной точке?

Любая помощь приветствуется.

Спасибо


person andyaladdin    schedule 09.12.2020    source источник


Ответы (1)


Вы можете определить apiRouter как фабричную функцию и передать ей функцию startNode. Затем вы можете call в своем роутере:

// 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;
}
person eol    schedule 09.12.2020
comment
@andyaladdin: есть отзывы? - person eol; 09.12.2020