All files / models token.ts

60% Statements 6/10
0% Branches 0/3
0% Functions 0/1
60% Lines 6/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48  3x 3x   3x                                                             3x                 3x   3x  
import { Token } from "@app/types/token";
import { Schema, model } from "mongoose";
import jwt, { JwtPayload } from "jsonwebtoken";
 
const tokenSchema = new Schema<Token>(
  {
    type: {
      type: String,
      required: true,
    },
    token: {
      type: String,
      required: true,
    },
    userId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    organizationId: {
      type: Schema.Types.ObjectId,
      ref: "Organization",
      required: false,
    },
    expiredAt: {
      type: Date,
      required: false,
      expires: "0s", // this will delete document automatically on set date
    },
  },
  {
    timestamps: true,
  }
);
 
tokenSchema.pre("save", function (next) {
  // it will make token collection clean by automatically deleting all expired tokens itself
  const tokenPayload = jwt.decode(this.token) as JwtPayload;
  Iif (tokenPayload && tokenPayload.exp) {
    this.expiredAt = new Date(tokenPayload.exp * 1000);
  }
  next();
});
 
const tokenModel = model<Token>("Token", tokenSchema);
 
export default tokenModel;