postgresql - 如何从表中删除已超过 PostgreSQL 过期限制的所有条目?

标签 postgresql express sequelize.js

我正在使用 PostgreSQL Sequelize ORM 。我在数据库中有一个 token 表,用于存储新用户的电子邮件验证 token 。我想以这样的方式设置 token ,即 token 在固定的时间间隔后过期,这意味着具有创建时间戳(例如 1 天前)的 token 应该从表中删除。

我在 google 上搜索,其中一个建议是使用触发器,并且在每次插入条目时,触发器都会调用存储过程以根据上述标准删除所有条目。但是这种方法在我的用例中存在漏洞。

以下代码是我目前使用的user.js模型文件

'use strict';
const _ = require("lodash");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    email: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: false
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    },
    role: {
      type: DataTypes.STRING,
      allowNull: false
    },
    verified: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    }
  }, {});

  User.associate = function(models) {
    User.hasMany(models.Code);
    User.hasOne(models.Token);
  }

  User.authenticate = async function(email, password) {
    const user = await User.findOne({where: { email }});
    if (!user) {
      throw new Error("Email not registered");
    }

    const result = await bcrypt.compare(password, user.password);
    if (!result) {
      throw new Error("Password is incorrect");
    }

    return user.authorize();
  }

  User.prototype.authorize = async function() {
      const user = _.pick(this.toJSON(), ["id", "email", "name", "role"]);
      const token = jwt.sign(user, process.env.JWT_SECRET, {
        expiresIn: 1440
      });

      return { user, token};
  };
  return User;
};

最佳答案

您可以为此使用 cron :

var CronJob = require('cron').CronJob;
console.log('Before job instantiation');
const job = new CronJob('0 1 * * * *', function() {
    const d = new Date();
  console.log(d);
  // write the code for delete 
});
console.log('After job instantiation');
job.start();

MORE EXAMPLE

关于postgresql - 如何从表中删除已超过 PostgreSQL 过期限制的所有条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57857541/

相关文章:

python - Django - 在同一模型中有多个外键

mysql - SQL 模式设计建议

node.js - 如何在一个 get 请求中返回多个 Mongoose 集合?

node.js - Express JS 多应用中间件

mysql - Sequelize 获取查询的所有数据而不执行我的条件 'where'

javascript - Sequelize : Using Multiple Databases

sequelize.js - Sequelize - 我可以根据另一个模型关系关联模型吗?

python - 带有 OSX Mavericks 和 Psycopg2 的 PostgreSQL 无法连接到 Mac 上的 Django Localhost

django - 在冲突做更新

node.js - 如何以正确的方式将 PostgreSQL 连接到 NodeJS?