node-mongo-demo

node.js and mongodb demo

git clone https://9o.is/git/node-mongo-demo.git

lucky7-session.js

(1400B)


      1 import mongoose from 'mongoose';
      2 import timer from '../utils/timer.js';
      3 
      4 const GAME_INTERVAL_IN_SECONDS = 15;
      5 const GAME_UNPLAYABLE_IN_SECONDS = 5;
      6 const EXPIRES_IN_SECONDS = 86400; // 1 day
      7 
      8 const lucky7SessionSchema = mongoose.Schema({
      9     userId: { type: 'ObjectId', ref: 'User', required: true, unique: true },
     10     createdAt: { type: Date, expires: EXPIRES_IN_SECONDS, default: Date.now },
     11 }, {
     12     virtuals: {
     13         expiresAt: {
     14             get() {
     15                 const millis = EXPIRES_IN_SECONDS * 1000;
     16                 return new Date(this.createdAt.getTime() + millis);
     17             },
     18         },
     19         gameIntervalInSeconds: {
     20             get() {
     21                 return GAME_INTERVAL_IN_SECONDS;
     22             },
     23         },
     24     },
     25     methods: {
     26         nextIntervalAt() {
     27             return timer(this).nextIntervalAt;
     28         },
     29         isPlayable() {
     30             const { nextIntervalAt, nextIntervalInMillis } = timer(this);
     31             return nextIntervalInMillis > GAME_UNPLAYABLE_IN_SECONDS * 1000;
     32         },
     33     },
     34     statics: {
     35         findByUserId(userId) {
     36             return this.findOne({ userId });
     37         },
     38         findByUserIdOrCreate(userId) {
     39             return this.findOneAndUpdate({ userId }, {}, {
     40                 upsert: true,
     41                 new: true,
     42             });
     43         },
     44     },
     45 });
     46 
     47 export default mongoose.model('Lucky7Session', lucky7SessionSchema);