【问题标题】:JSON Server - Using a cronjob to update the databaseJSON 服务器 - 使用 cronjob 更新数据库
【发布时间】:2020-01-18 18:25:30
【问题描述】:

我正在尝试使用JSON server 创建一个 API,从而定期以编程方式添加新数据。

目标是每小时从另一个 api 查询数据,并用这些新数据更新数据库。

目前我正在关注文档中的示例,并添加了节点 cron 模块的使用:

// index.js
var cron = require('cron').CronJob;

module.exports = () => {
 const data = {
  categories: []
 };

 const job = new cron('*/4 * * * * *', function() {
  const d = new Date();
  data.categories.push(d);

  console.log('array updated')
 });

 job.start();

 return data;
};

这不起作用,数组保持为空。

我想知道更新数据库的解决方案是什么样的?

我的服务器代码如下所示:

const jsonServer = require('json-server')
const fs = require('fs');
const jsonfetch = require('./index.js');
const server = jsonServer.create()

fs.writeFileSync('/tmp/db.json', JSON.stringify(jsonfetch()));

const router = jsonServer.router('/tmp/db.json')

const options = {
  static: __dirname + '/public'
}

const middlewares = jsonServer.defaults(options)
const port = process.env.PORT || 3000

server.use(middlewares)
server.use('/api', router)

server.listen(port, () => {
  console.log('JSON Server is running on ' + port)
})

【问题讨论】:

    标签: node.js json json-server


    【解决方案1】:

    我以前使用 npm node-cron 库做过类似的事情。这是一个基本示例,但我也编写了一个 es6 类,因此如果您愿意,我可以为您提供更复杂的内容。

    import axios from 'axios'
    
    let node_cron = require('node-cron');
    
    node_cron.schedule('* * * * *', async function () {
       // Do your thing here.
    }

    【讨论】:

    • 感谢@banderson,但它似乎没有工作。我认为这是因为在 index.js 中执行 cron 作业之前返回数据,但在 cron 作业中返回数据破坏代码。让 node_cron = require('node-cron'); module.exports = () => { const data = { categories: [ ] }; node_cron.schedule('*/3 * * * * *', async function () { data.categories.push('test'); console.log('pushed') });返回数据; };
    • @ogot 我能够在每个 cron 间隔进行控制台日志。问题可能是返回语句。为什么需要返回更新数据库?你可以做一个异步等待然后插入到数据库中。将 .catch 链接到 await 和控制台记录发生的任何错误。
    • node_cron.schedule('* * * * *', async function () { console.log('Checking connectivity.'); await axios.post(${endpoint}, { user_email: "banderson@banderson.com" }, { }) .catch((err, res) => { console.log('error: ', err); console.log('res: ', res.body); }); });
    【解决方案2】:

    在nestJS 中,您可以使用@nestjs/schedule 和@types/cron 包来安排API 请求。

     1. npm install --save @nestjs/schedule
     2. npm install --save-dev @types/cron
    

    接下来将调度模块添加到 app.module.ts 文件中,如下所示。

    @Module({
        imports: [
          ScheduleModule.forRoot()
        ]
      )}
    

    然后用下面的装饰器添加实现功能。

     @Cron('60 * * * * *')
      public async getAllImges(): Promise<ImagesDto[]> {}
    

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多