首页 > 解决方案 > 如何在 Sails 0.12 中通过请求(在部分离线的情况下)连接到远程数据库

问题描述

我的 PC 在 Kiosk 模式下运行(自助服务亭)。它的互联网连接较弱,所以我使用本地 MongoDB 服务器来处理所有数据。但有时(例如每天)我想将统计数据和其他内容发送到远程数据库。当我启动 PC 时,当互联网连接断开时,我收到以下消息:

error: A hook (`orm`) failed to load!
error: Error: Failed to connect to MongoDB.  Are you sure your configured Mongo instance is running?
  Error details: { MongoError: connection 1 to ds241489.mlab.com:41489 timed out
    at Function.MongoError.create (/home/nevada/v4/node_modules/mongodb-core/lib/error.js:29:11)
    at Socket.<anonymous> (/home/nevada/v4/node_modules/mongodb-core/lib/connection/connection.js:186:20)
    ...

然后 Sails 崩溃并且浏览器向用户显示错误消息

连接.js:

mlab: {
  adapter: 'sails-mongo',
  host: 'ds241489.mlab.com',
  port: *****,
  user: '******',
  password: '************',
  database: '******'
}

模型/Remote.js:

module.exports = {
  connection: 'mlab',
  attributes: {
    // Some stuff here
  }
};

互联网可用时一切正常,但是当 PC 离线时,服务器拒绝启动。如何根据用户的请求跳过与(远程)数据库的自动连接,然后(尝试)手动连接?

标签: mongodbsails.jsofflinesails-mongoofflineapps

解决方案


I haven't implemented this myself, but I would do one of two things here:

  1. Set up a separate cron or other type of scheduled task to run every hour or so. This would then check for internet, and if internet connects successfully, run the DB-sync script. Of course inside a big try/catch to gracefully handle internet disconnect half way through.

  2. Set up an event-listener on the host/kiosk system, that listens for an event indicating that the OS has internet connection again. When that happens, try to run the script mentioned above.

Number one is the most likely candidate in my book, and I'd even throw in a Sails module to keep all logic in the controllers and config. sails-hook-cron (GitHub) is a very popular hook you can use to configure your cron-job in the config/cron.js file, and use it in a controller of your choosing.

Set up your application to NOT connect to Mlab automatically. Only do that in the sync-script, and the app should start without a hitch, regardless of your internet connection.


推荐阅读