MemberModel.ts 1.78 KB
Newer Older
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
1
import { arrayProp, getModelForClass, index, pre, prop, Severity } from '@typegoose/typegoose';
2
import DbDAO from '../../db/DbDAO';
3
import { DbCollection } from '../../enums/DbOperation';
4 5
import { IMemberSerialized } from '../../interfaces/entities/Member/IMemberSerialized';
import { IQuizResponse } from '../../interfaces/quizzes/IQuizResponse';
6
import { ICasData } from '../../interfaces/users/ICasData';
7

8 9 10
@index({
  name: 1,
  currentQuizName: 1,
11 12 13 14 15 16 17 18 19 20 21 22
}, {
  unique: true,
  collation: {
    locale: 'en',
    strength: 1,
  },
}) //
@pre<MemberModelItem>(/.*/, function (): void {
  if (!this.colorCode && this.name) {
    this.colorCode = generateRandomColorCode(this.name);
  }
})
23
export class MemberModelItem implements IMemberSerialized {
24 25 26
  @prop() public colorCode: string;
  @prop({ required: false }) public groupName: string;
  @prop() public name: string;
27
  @arrayProp({ items: Object }) public responses: Array<IQuizResponse>;
28 29 30
  @prop({ required: false }) public ticket: string;
  @prop() public token: string;
  @prop() public currentQuizName: string;
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
  @prop() public casProfile: ICasData;
}

function hashCode(str: string): number { // java String#hashCode
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  return hash;
}

function intToRGB(i: number): string {
  const c: string = (i & 0x00FFFFFF)
  .toString(16)
  .toUpperCase();

  return '00000'.substring(0, 6 - c.length) + c;
}

function generateRandomColorCode(name: string): string {
  return intToRGB(hashCode(name));
52 53
}

54
export const MemberModel = getModelForClass(MemberModelItem, {
55 56 57 58 59
  schemaOptions: {
    collection: DbCollection.Members,
    timestamps: true,
  },
  existingConnection: DbDAO.dbCon,
Christopher Mark Fullarton's avatar
Christopher Mark Fullarton committed
60 61 62 63
  options: {
    runSyncIndexes: true,
    allowMixed: Severity.ALLOW,
  },
64 65
});