All files / ragchat-api/models User.js

85.29% Statements 116/136
100% Branches 0/0
0% Functions 0/1
85.29% Lines 116/136

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 1361x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x
import { Schema, model } from 'mongoose';
import bcrypt from 'bcrypt';
import mongooseUniqueValidator from 'mongoose-unique-validator';
 
 
// ################################# SCHEMA OPTIONS
const opts = {
  timestamps: true,
  toObject: { virtuals: true },
  toJSON: { virtuals: true },
  strict: true,
  strictQuery: false // Turn off strict mode for query filters
};
 
// ################################# SCHEMA
const UserSchema = new Schema(
  {
    username: {
      type: String,
      title: 'Username'
    },
    name: {
      type: String,
      title: 'Name'
    },
    email: {
      type: String,
      title: 'eMail',
      required: true,
      lowercase: true,
      unique: true,
    },
    password: {
      type: String,
      title: 'Password',
      select: false
    },
    resetPasswordToken: {
      type: String,
      title: 'Password Token'
    },
    verified: {
      type: Boolean,
      title: 'Validated',
      default: false
    },
    role: {
      type: Number,
      title: 'Role',
      default: 0
    },
    refreshToken: {
      type: String,
      title: 'Refresh Token',
      select: false
    },
    updatedBy: {
      type: Schema.Types.ObjectId,
      title: 'updated by',
      ref: "User"
    },
    createdBy: {
      type: Schema.Types.ObjectId,
      title: 'created by',
      ref: "User"
    }
  },
  opts
);
 
// ################################# VIRTUALS
// fullName
// UserSchema.virtual('fullname').get(function () {
//   return `${this.title || ''} ${this.firstname || ''} ${this.lastname || ''}`.replace(/\s+/g, ' ').trim();
// });
 
// ################################# MIDDLEWARES
// middleware pre|post on validate|save|remove|updateOne|deleteOne 
// pre save
UserSchema.pre('save', async function (next) {
  // remember editor
  if (this.isNew) {
    this.createdBy = global.currentUserId;
  } else {
    this.updatedBy = global.currentUserId;
  }

  // hash password
  if (this.isModified('password')) {
    const hashedPassword = await bcrypt.hash(this.password, Number(process.env.BCRYPT_STRENGTH));
    this.password = hashedPassword;
  }
  // go on
  next();
});
 
 
 
// ################################# STATICS
// example static function | only avail on User directly like User.findByMail('a@b.c')
// UserSchema.statics.findByMail = function(email){
//   return this.find({email: new RegExp(email, "i")})
// }
 
// ################################# QUERY HELPERS
// example chainable query function | only avail chained on User query like User.find().byMail('a@b.c')
// UserSchema.query.byMail = function(email){
//   return this.where({email: new RegExp(email, "i")})
// }
 
// ################################# INSTANCE METHODS
// example method
// UserSchema.methods.fullName = function () {
//   return `${this.title} ${this.firstname} ${this.lastname}`;
// };
 
 
/**
 * Validate unique fields in the following function
 * because default mongoose 'unique: true' isn't handled as validation error
 */
UserSchema.plugin(mongooseUniqueValidator, { message: 'Record with this {PATH} already exists.' });
 
/**
 * return all confidential fieldnames
 * based on 'select: false'
 */
UserSchema.methods.getConfidentialFields = function () {
  const schema = Object.entries(User.schema.paths);
  const confidentialFields = schema.filter(function (field) {
    return field[1].selected === false;
  });
  return confidentialFields.map(field => field[0]);
};
 
export default model('User', UserSchema);