首页 文章

仅在Koa v2中的服务器启动时执行一次中间件

提问于
浏览
0

我创建了这个中间件,当网站中的任何路由获得访问者的第一个命中时,它只执行一次:

// pg-promise
const db = require('./db/pgp').db;
const pgp = require('./db/pgp').pgp;

app.use(async (ctx, next) => {
  try {
    ctx.db = db;
    ctx.pgp = pgp;
  } catch (err) {
    debugErr(`PGP ERROR: ${err.message}` || err);
  }
  await next();
});

// One-Time middleware
// https://github.com/expressjs/express/issues/2457
const oneTime = (fn) => {
  try {
    let done = false;
    const res = (ctx, next) => {
      if (done === false) {
        fn(ctx, next);
        done = true;
      }
      next();
    };
    return res;
  } catch (err) {
    debugErr(`oneTime ERROR: ${err.message}` || err);
  }
};

const oneTimeQuery = async (ctx) => {
  const result = await ctx.db.proc('version', [], a => a.version);
  debugLog(result);
};

app.use(oneTime(oneTimeQuery));

此代码仅在用户访问网站时首次执行,从而导致:

app:log Listening on port 3000 +13ms
app:req GET / 200 - 24ms +2s
23:07:15 connect(postgres@postgres)
23:07:15 SELECT * FROM version()
23:07:15 disconnect(postgres@postgres)
app:log PostgreSQL 9.6.2, compiled by Visual C++ build 1800, 64-bit +125ms

我的问题是我想在服务器启动时执行它,当时网站上没有任何访问 .

此代码的未来目的是检查数据库中表的存在 .

Solution:

const server = http.createServer(app.callback()); 声明之前将其放在 ./bin/www 中有助于:

const query = async () => {
  const db = require('../db/pgp').db;
  const pgp = require('../db/pgp').pgp;
  const result = await db.proc('version', [], a => a.version);
  debugLog(`www: ${result}`);
  pgp.end(); // for immediate app exit, closing the connection pool (synchronous)
};
query();

1 回答

  • 1

    您可以使用需要应用程序的js脚本启动应用程序,并使用节点的本机http模块启动服务器 . 完全像在koa发电机(click) .

    这是在你的app.js文件中:

    const app = require('koa')();
    ...
    module.exports = app;
    

    然后这是在您的脚本中启动服务器:

    const app = require('./app');
    const http = require('http');
    
    [this is the place where you should run your code before server starts]
    
    const server = http.createServer(app.callback());
    server.listen(port);
    

    然后你开始申请:

    node [script_name].js
    

    当然,这样做时要记住节点的异步性质 . 我的意思是 - 在回调/保证中对'server'变量运行'listen'方法 .

相关问题