lora-project/server-api/libs/mongo_model.js
2017-06-04 21:38:14 +08:00

40 lines
1.2 KiB
JavaScript

const mongoose = require('mongoose');
const tokenSchema = mongoose.Schema({
object: Object,
expire: {
type: Number,
default: Date.now
}
});
tokenSchema.statics.clearExpire = function (cb) {
console.log(Date.now())
return this.remove({ expire: { $lte: Date.now() } }, cb);
}
tokenSchema.statics.renewToken = function (id, expire, cb) {
return this.update({ _id: mongoose.Schema.Types.ObjectId(id) }, { $set: { expire: Date.now() + 86400000 } }, cb);
}
tokenSchema.statics.checkToken = async function (str) {
let self = this;
return new Promise((resolve, reject) => {
self.findOne({ _id: str, expire: { $gte: Date.now() } }, (err, row) => {
if (err || !row) return resolve(false);
return resolve(true);
});
})
}
tokenSchema.statics.getToken = async function (str) {
let self = this;
return new Promise((resolve, reject) => {
self.findOne({ _id: str, expire: { $gte: Date.now() } }, (err, row) => {
if (err) return reject(err);
return resolve(row);
})
})
}
const token = mongoose.model('token', tokenSchema, 'token');
module.exports = {
token
}