Как включить маршрут Express.post один раз в день - PullRequest
0 голосов
/ 01 октября 2019

У меня есть приложение express.js, которое позволяет пользователю публиковать акт. Я хочу ограничить эти сообщения до одного в день. Начиная со стороны сервера, я хочу изменить маршрут публикации только в том случае, если текущим пользователем в тот же день уже не был опубликован акт. В текущем маршруте (показанном ниже) я пытаюсь сравнить текущую дату в 00:00 с датой созданного_дата последнего акта пользователя st, что при созданном_дате> = start_of_current_date сообщение не будет появляться. Тем не менее, create_at записывается, но возвращает неопределенное в условном выражении.

Вот мой маршрут:

// POST new Act route 
router.post('/', auth.required, async (req, res, next) => {
  const now = new Date();
  // return last created Act
  result = await Act
    .query()
    .where('users_id', req.user.id)
    .orderBy('created_at', 'desc')
    .limit(1);

  console.log('this is the last act of user ', req.user.id, ': ', result);
  console.log('this is the created_at last act of user ', req.user.id, ': ', result.created_at);
  console.log('this is the start of today ', req.user.id, ': ', now.setHours(0,0,0,0));

  // conditional to disable if last Act.created_at == Today
  if(result.created_at >= now.setHours(0,0,0,0)) {
    return Act.query()
    .insert({
      deed: req.body.act.deed,
      users_id: req.body.act.userId
    }) 
    .then( function () {
      res.json({ success: true, message: 'ok' });     // respond back to request
    })
  } else {
    res.json ({
      "message": "This user already acted today."
    });
  }
});

Вот результат в консоли, включая журналы моей консоли:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Running on localhost:8000
this is the last act of user  1 :  [ Act {
    id: 6,
    deed: 'Writing',
    users_id: 1,
    created_at: 2019-09-23T20:04:28.393Z,
    updated_at: 2019-09-23T20:04:28.393Z } ]
this is the created_at last act of user  1 :  undefined
this is the start of today  1 :  1569902400000

ОБНОВЛЕНИЕ: результат возвращает массив, поэтому, используя результат [0], я могу получить значение. h / e, необходимо преобразовать выходные данные, чтобы сравнить их с текущей датой. Вот токовый выход:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Running on localhost:8000
this is the last act of user  1 :  [ Act {
    id: 6,
    deed: 'Writing',
    users_id: 1,
    created_at: 2019-09-23T20:04:28.393Z,
    updated_at: 2019-09-23T20:04:28.393Z } ]
this is the date of the last act of user  1 :  2019-09-23T20:04:28.393Z
this is the start of today  1 :  1569902400000

1 Ответ

0 голосов
/ 01 октября 2019

это работает, используя помощник getTime ():

// POST new act route 
router.post('/', auth.required, async (req, res, next) => {
  const now = new Date();
  // return last created Act
  result = await Act
    .query()
    .where('users_id', req.user.id)
    .orderBy('created_at', 'desc')
    .limit(1);

  console.log('this is the last act of user ', req.user.id, ': ', result);
  console.log('this is the date of the last act of user ', req.user.id, ': ', result[0].created_at.getTime());
  console.log('this is the start of today ', req.user.id, ': ', now.setHours(0,0,0,0));

  // conditional to disable if last Act.created_at == Today
  if(result[0].created_at.getTime() <= now.setHours(0,0,0,0)) {
    return Act.query()
    .insert({
      deed: req.body.act.deed,
      users_id: req.body.act.userId
    }) 
    .then( function () {
      res.json({ success: true, message: 'ok' });     // respond back to request
    })
  } else {
    res.json ({
      "message": "This user already acted today."
    });
  }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...