Index

test/entity/contact.mock.ts

addContact
Default value : async ( data: IContactData ): Promise<ContactEntity> => { const contact = getContactStub(data); return getConnection().getRepository(ContactEntity).save(contact); }
checkContact
Default value : async (response: any) => { const contactId = response.id; const contactDB = await getContactById(contactId); expect(omit(response, ['createdAt', 'updatedAt'])).toEqual( omit({ ...contactDB }, ['createdAt', 'updatedAt', 'userId', 'user']) ); expect(response.createdAt).toBe(contactDB.createdAt.toISOString()); expect(response.updatedAt).toBe(contactDB.updatedAt.toISOString()); }
getContactById
Default value : async (id: number): Promise<ContactEntity> => { return getConnection().getRepository(ContactEntity).findOne(id); }
getContactStub
Default value : (data?: IContactData): ContactEntity => { const contact = new ContactEntity(); contact.id = data?.id; contact.email = data?.email ?? faker.internet.email(); contact.phone = data?.phone ?? getRandomPhoneNumber(); contact.prefix = data?.prefix ?? getRandomPhonePrefix(); contact.name = data?.name ?? faker.name.firstName(); contact.surname = data?.surname ?? faker.name.lastName(); contact.userId = data?.userId; contact.active = data?.active ?? faker.datatype.boolean(); return contact; }
getRandomPhoneNumber
Default value : (): string => faker.datatype .number({ min: 999, max: 999999999999, }) .toString()
getRandomPhonePrefix
Default value : (): number => faker.datatype.number({ min: 1, max: 999, })

src/contact/request/schema/add-contact-and-check-phone.schema.ts

addContactAndCheckPhoneSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ ...profileSchema, countryCode: Joi.string(), }) .and('prefix', 'phone', 'countryCode') .or('phone', 'email') .options({ presence: 'optional', })

src/contact/request/schema/add-contact.schema.ts

addContactSchema
Type : Joi.ObjectSchema
Default value : Joi.object(profileSchema) .and('prefix', 'phone') .or('phone', 'email') .options({ presence: 'optional', })

src/file/request/schema/add-file.schema.ts

addFileSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ category: Joi.string() .valid(...Object.values(CATEGORY)) .required(), })

test/entity/profile.mock.ts

addProfile
Default value : async ( data?: IProfileData ): Promise<ProfileEntity> => { const profile = getProfileStub(data); return getConnection().getRepository(ProfileEntity).save(profile); }
checkProfile
Default value : async (response: any) => { const userId = response.userId; const profileDB = await getProfileById(userId); const userDB = await getUserById(userId); expect( omit(response, [ "createdAt", "updatedAt", "dateOfBirth", "lastHospitalVisit", "deviceId", ]) ).toEqual( omit( { ...profileDB, prefix: Number(profileDB.prefix), }, [ "createdAt", "updatedAt", "contacts", "dateOfBirth", "lastHospitalVisit", "regularNotificationTime", "user", "id", ] ) ); if (response.deviceId) { expect(response.deviceId).toBe(userDB.deviceId); } if (response.dateOfBirth) { expect(response.dateOfBirth).toBe( moment(profileDB.dateOfBirth).format("DD/MM/YYYY") ); } if (response.lastHospitalVisit) { expect(response.lastHospitalVisit).toBe( moment(profileDB.lastHospitalVisit).format("DD/MM/YYYY") ); } expect(response.createdAt).toBe(profileDB.createdAt.toISOString()); expect(response.updatedAt).toBe(profileDB.updatedAt.toISOString()); }
getProfileById
Default value : async ( userId: string ): Promise<ProfileEntity> => { return getConnection() .getRepository(ProfileEntity) .findOne({ where: { userId }, relations: ["user"] }); }
getProfileStub
Default value : (data: IProfileData): ProfileEntity => { const profile = new ProfileEntity(); profile.userId = data.userId; profile.name = data?.name ?? faker.name.firstName(); profile.surname = data?.surname ?? faker.name.lastName(); profile.prefix = data?.prefix !== undefined ? data.prefix : getRandomPhonePrefix(); profile.location = data?.location; profile.phone = data?.phone !== undefined ? data.phone : getRandomPhoneNumber(); profile.emergencyMessage = data?.emergencyMessage ?? faker.lorem.sentence(); profile.address = data?.address ?? `${faker.address.streetName()}, ${faker.address.city()}, ${faker.address.country()}`; profile.dateOfBirth = data?.dateOfBirth ?? moment().toDate(); profile.primaryPhysician = data?.primaryPhysician ?? `${faker.name.firstName()} ${faker.name.lastName()}`; profile.primaryPhysicianAddress = data?.primaryPhysicianAddress ?? `${faker.address.streetName()}, ${faker.address.city()}, ${faker.address.country()}`; profile.seriousMedicalIssues = data?.seriousMedicalIssues !== undefined ? data.seriousMedicalIssues : faker.datatype.boolean(); profile.mostRecentDiagnosis = data?.mostRecentDiagnosis !== undefined ? data.mostRecentDiagnosis : faker.lorem.sentence(); profile.lastHospitalVisit = data.lastHospitalVisit !== undefined ? data.lastHospitalVisit : moment().toDate(); profile.emergencyEmailAndSms = data?.emergencyEmailAndSms !== undefined ? data.emergencyEmailAndSms : faker.datatype.boolean(); profile.locationAccess = data?.locationAccess !== undefined ? data.locationAccess : faker.datatype.boolean(); profile.readManual = data?.readManual !== undefined ? data.readManual : faker.datatype.boolean(); profile.automatedEmergency = data?.automatedEmergency !== undefined ? data.automatedEmergency : faker.datatype.boolean(); profile.positiveInfoPeriod = data?.positiveInfoPeriod; profile.frequencyOfRegularNotification = data?.frequencyOfRegularNotification; profile.regularPushNotification = data?.regularPushNotification; return profile; }
updateProfile
Default value : async ( id: number, data: { emergencyEmailAndSms?: boolean; } ): Promise<UpdateResult> => { return getConnection().getRepository(ProfileEntity).update(id, data); }

test/entity/trigger-time-slot.mock.ts

addTimeSlot
Default value : async ( data: ITimeSlotData ): Promise<TimeSlotEntity> => { const timeSlot = getTimeSlotStub(data); return getConnection() .getRepository(TimeSlotEntity) .save({ ...timeSlot, days: data.days, }); }
checkTimeSlot
Default value : async (response: any) => { const timeSlotId = response.id; const timeSlotDB = await getTimeSlotById(timeSlotId); expect( omit( { ...response, to: String(response.to), }, ['days'] ) ).toEqual( omit( { ...timeSlotDB, from: timeSlotDB.from ? timeSlotDB.from.toISOString() : null, to: timeSlotDB.to.toISOString(), createdAt: timeSlotDB.createdAt.toISOString(), }, ['days', 'userId'] ) ); expect( timeSlotDB.days .map((item) => getEnumKeyByValue(DAYS_OF_WEEKS, item.day)) .sort() ).toEqual(response.days.sort()); }
getTimeSlotById
Default value : async (id: number): Promise<TimeSlotEntity> => { return getConnection() .getRepository(TimeSlotEntity) .findOne({ where: { id }, relations: ['days'], }); }
getTimeSlotStub
Default value : (data?: ITimeSlotData): TimeSlotEntity => { const timeSlot = new TimeSlotEntity(); timeSlot.id = data?.id; timeSlot.active = data?.active ?? faker.datatype.boolean(); timeSlot.from = data?.from !== undefined ? data.from : moment().toDate(); timeSlot.to = data?.to ?? moment().toDate(); timeSlot.userId = data.userId; return timeSlot; }

src/trigger-time-slot/request/schema/add-time-slot.schema.ts

addTimeSlotSchema
Type : Joi.ObjectSchema
Default value : Joi.object( timeSlotSchema ).options({ presence: 'optional', })

test/entity/user.mock.ts

addUser
Default value : async (data?: IUserData): Promise<UserEntity> => { const user = getUserStub(data); return getConnection().getRepository(UserEntity).save(user); }
checkUser
Default value : async (response: any) => { const userId = response.id; const userDB = await getUserById(userId); expect( omit(response, [ 'createdAt', 'updatedAt', 'dateOfBirth', 'lastHospitalVisit', 'fillLevel', 'prefix', 'isEmergencyTriggerActive', ]) ).toEqual( omit( { ...userDB.profile, allowNotifications: userDB.profile.allowNotifications !== false, tipsAndTricks: userDB.profile.tipsAndTricks !== false, emergencyEmailAndSms: userDB.profile.emergencyEmailAndSms !== false, uploadedDocumentsAccess: userDB.profile.uploadedDocumentsAccess !== false, locationAccess: !!userDB.profile.locationAccess, readManual: !!userDB.profile.readManual, automatedEmergency: !!userDB.profile.automatedEmergency, regularPushNotification: !!userDB.profile.regularPushNotification, pulseBasedTriggerIOSHealthPermissions: !!userDB.profile.pulseBasedTriggerIOSHealthPermissions, pulseBasedTriggerIOSAppleWatchPaired: !!userDB.profile.pulseBasedTriggerIOSAppleWatchPaired, pulseBasedTriggerGoogleFitAuthenticated: !!userDB.profile.pulseBasedTriggerGoogleFitAuthenticated, pulseBasedTriggerConnectedToGoogleFit: !!userDB.profile.pulseBasedTriggerConnectedToGoogleFit, pulseBasedTriggerBackgroundModesEnabled: !!userDB.profile.pulseBasedTriggerBackgroundModesEnabled, ...userDB, }, [ 'prefix', 'createdAt', 'updatedAt', 'profile', 'dateOfBirth', 'lastHospitalVisit', 'userId', 'regularNotificationTime', ] ) ); expect(response.fillLevel).toBeDefined(); if (response.prefix) { expect(response.prefix).toBe(Number(userDB.profile.prefix)); } if (response.dateOfBirth) { expect(response.dateOfBirth).toBe( moment(userDB.profile.dateOfBirth).format('DD/MM/YYYY') ); } if (response.lastHospitalVisit) { expect(response.lastHospitalVisit).toBe( moment(userDB.profile.lastHospitalVisit).format('DD/MM/YYYY') ); } expect(response.createdAt).toBe(userDB.createdAt.toISOString()); expect(response.updatedAt).toBe(userDB.updatedAt.toISOString()); }
getUserById
Default value : async (id: string): Promise<UserEntity> => { return getConnection() .getRepository(UserEntity) .findOne({ where: { id }, relations: ['profile'] }); }
getUserStub
Default value : (data?: IUserData): UserEntity => { const user = new UserEntity(); user.id = faker.datatype.uuid(); user.email = data?.email ?? faker.internet.email(); return user; }

test/mock/auth.guard.mock.ts

authGuardMock
Type : object
Default value : { canActivate: async (context) => { const request = context.switchToHttp().getRequest(); const token = request.headers.authorization; if (token) { request.user = await getConnection() .getRepository(UserEntity) .findOne(token); if (!request.user) { return false; } } return true; }, }

src/file/provider/aws-cloud-front-sign.provider.ts

AWSCloudFrontSignerProvider
Type : object
Default value : { provide: DICTIONARY.CLOUD_FRONT_SIGNER, inject: [ConfigService], useFactory: (config: ConfigService) => { return new AWS.CloudFront.Signer( config.get('cloudFrontSigner.accessKeyId'), config.get('cloudFrontSigner.privateKey') ); }, }

src/file/provider/aws-s3.provider.ts

AWSS3Provider
Type : object
Default value : { provide: DICTIONARY.S3, inject: [ConfigService], useFactory: (config: ConfigService) => { return new AWS.S3({ accessKeyId: config.get('s3.accessKeyId') || undefined, signatureVersion: 'v4', secretAccessKey: config.get('s3.secretAccessKey') || undefined, }); }, }

src/user/mapper/user.mapper.ts

calculatePercentByWeight
Default value : (user: UserEntity): number => { let weightOfValues = 0; let sumOfWeights = 0; const weightList = Object.entries(PROFILE_WEIGHT).filter(([, value]) => Number.isInteger(value) ); for (const [key, value] of weightList) { sumOfWeights += Number(value); if ( isDefined(user[key]) || (user.profile && isDefined(user.profile[key])) || (user?.profile?.seriousMedicalIssues !== true && ['mostRecentDiagnosis', 'lastHospitalVisit'].includes(key)) || (user?.profile?.regularPushNotification !== true && key === 'frequencyOfRegularNotification') || (user?.profile?.regularPushNotification === true && key === 'positiveInfoPeriod') ) { weightOfValues += Number(value); } } return (weightOfValues / sumOfWeights) * 100; }
userMapper
Default value : (user: UserEntity, trigger: Bull.Job): UserRO => { return plainToClass(UserRO, { ...user.profile, ...getProfileDefaultValues(user?.profile), ...user, fillLevel: Math.round(calculatePercentByWeight(user)), isEmergencyTriggerActive: trigger ? !!trigger : undefined, }); }

src/common/helper/check-phone-number.ts

checkPhoneNumber
Default value : ( phoneUtil: LibPhoneNumber.PhoneNumberUtil, prefix: number, phone: string, country: string ): boolean => { const number = phoneUtil.parseAndKeepRawInput(`+${prefix}${phone}`, country); return phoneUtil.isValidNumber(number); }

test/helper/index.ts

clearDatabase
Default value : async (): Promise<void> => { const connection = getConnection(); try { await connection.query(`SET FOREIGN_KEY_CHECKS = 0;`); for (const entity of connection.entityMetadatas) { if (entity.tableMetadataArgs.name !== 'file_category') { await connection .getRepository(entity.name) .query(`TRUNCATE table ${entity.tableMetadataArgs.name};`); } } await connection.query(`SET FOREIGN_KEY_CHECKS = 1;`); } catch (error) { await getConnection().query(`SET FOREIGN_KEY_CHECKS = 1;`); throw new Error(`ERROR: Cleaning test db: ${error}`); } }

test/mock/cloud-front-signer.mock.ts

cloudFrontSignerMock
Type : object
Default value : { getSignedUrl: jest.fn(() => faker.image.imageUrl()), }

test/mock/cognito-identity-service.mock.ts

cognitoIdentityServiceMock
Type : object
Default value : { adminAddUserToGroup: jest.fn(async () => ({})), adminCreateUser: jest.fn(async () => ({})), listUsers: jest.fn( async ( params: AWS.CognitoIdentityServiceProvider.Types.ListUsersRequest, callback: () => void ) => ({}) ), adminDeleteUser: jest.fn((params, cb) => cb()), adminSetUserPassword: jest.fn(async () => ({})), adminUpdateUserAttributes: jest.fn((params, cb) => cb()), }

src/common/provider/cognito-identity-service.provider.ts

CognitoIdentityServiceProvider
Type : object
Default value : { provide: AWS.CognitoIdentityServiceProvider, inject: [ConfigService], useFactory: (config: ConfigService) => { AWS.config.update({ accessKeyId: config.get('authorization.accessKeyId') || undefined, secretAccessKey: config.get('authorization.secretAccessKey') || undefined, region: config.get('authorization.region'), }); return new AWS.CognitoIdentityServiceProvider(); }, }

src/app.module.ts

config
Default value : configuration()

src/main.ts

config
Default value : configuration()

test/mock/config.mock.ts

configMock
Type : object
Default value : { get: jest.fn((key: number | string) => { const data = flat(configuration()); return data[key]; }), }

src/common/provider/config.provider.ts

ConfigProvider
Type : object
Default value : { provide: DICTIONARY.CONFIG, useExisting: ConfigService, }

src/common/validation/config.validation.ts

configSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ APP_PORT: Joi.number(), NODE_ENV: Joi.string() .valid('development', 'production', 'stage', 'test') .default('development'), DB_USERNAME: Joi.string(), DB_DATABASE: Joi.string(), DB_PASSWORD: Joi.string(), DB_HOST: Joi.string(), DB_PORT: Joi.number().default(3306), GLOBAL_PREFIX: Joi.string(), COGNITO_ACCESS_KEY_ID: Joi.string().optional().allow(''), COGNITO_SECRET_ACCESS_KEY: Joi.string().optional().allow(''), COGNITO_USER_POOL_ID: Joi.string(), COGNITO_CLIENT_ID: Joi.string(), COGNITO_REGION: Joi.string(), BACKEND_URL: Joi.string(), MAILJET_API_KEY: Joi.string(), MAILJET_API_SECRET: Joi.string(), MAILJET_EMAIL: Joi.string(), MAILJET_USERNAME: Joi.string(), TWILIO_ACCOUNT_SID: Joi.string(), TWILIO_AUTH_TOKEN: Joi.string(), TWILIO_PHONE_NUMBER: Joi.string(), REDIS_SCHEMA: Joi.string(), REDIS_USER: Joi.string(), REDIS_HOST: Joi.string(), REDIS_PORT: Joi.number(), REDIS_PASSWORD: Joi.string(), S3_ACCESS_KEY_ID: Joi.string().optional().allow(''), S3_SECRET_ACCESS_KEY: Joi.string().optional().allow(''), S3_BUCKET: Joi.string(), S3_URL: Joi.string(), FIREBASE_ACCOUNT_KEY: Joi.string(), ENCRYPTION_IV: Joi.string().required(), ENCRYPTION_KEY: Joi.string().required(), }).options({ allowUnknown: true, presence: 'required' })

src/user/request/schema/confirm-user-email.schema.ts

confirmUserEmailSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ code: Joi.string().guid().required(), })

test/mock/connection.mock.ts

connectionMock
Type : object
Default value : { createQueryRunner: jest.fn(() => ({ startTransaction: jest.fn(async () => ({})), commitTransaction: jest.fn(async () => ({})), rollbackTransaction: jest.fn(async () => ({})), release: jest.fn(async () => ({})), })), }

src/common/provider/connection.provider.ts

ConnectionProvider
Type : object
Default value : { provide: DICTIONARY.CONNECTION, useFactory: () => getConnection(), }

src/common/error/keys.ts

CONTACT_NOT_FOUND
Type : string
Default value : 'E0004'
DELETE_CONTACT_FAILED
Type : string
Default value : 'E0007'
DELETE_FILE_FROM_DB_FAILED
Type : string
Default value : 'E0037'
DELETE_FILE_FROM_S3_FAILED
Type : string
Default value : 'E0036'
DELETE_TIME_SLOT_FAILED
Type : string
Default value : 'E0026'
DELETE_USER_FROM_COGNITO_FAILED
Type : string
Default value : 'E0040'
DELETE_USER_FROM_DB_FAILED
Type : string
Default value : 'E0041'
EMAIL_ALREADY_IN_USE
Type : string
Default value : 'E0010'
EMAIL_AND_SMS_NOT_ALLOWED
Type : string
Default value : 'E0017'
EXPORT_DATA_FAILED
Type : string
Default value : 'E0042'
FILE_CATEGORY_NOT_FOUND
Type : string
Default value : 'E0033'
FILE_IS_REQUIRED
Type : string
Default value : 'E0030'
FILE_IS_TOO_BIG
Type : string
Default value : 'E0032'
FILE_NOT_FOUND
Type : string
Default value : 'E0035'
FILE_TYPE_IS_INVALID
Type : string
Default value : 'E0031'
FILE_UPLOAD_FAILED
Type : string
Default value : 'E0029'
GET_FILE_CATEGORIES_FAILED
Type : string
Default value : 'E0039'
GET_FILE_CONTENT_FAILED
Type : string
Default value : 'E0043'
GET_FILE_URL_FAILED
Type : string
Default value : 'E0038'
GET_JOB_FAILED
Type : string
Default value : 'E0023'
JOB_REMOVE_FAILED
Type : string
Default value : 'E0022'
LIMIT_OF_NUMBER_OF_FILES_REACHED
Type : string
Default value : 'E0048'
LOCATION_DATA_IS_NEEDED
Type : string
Default value : 'E0018'
MESSAGE_IS_NEEDED
Type : string
Default value : 'E0019'
MINUTES_TO_NEXT_MESSAGE_ARE_REQUIRED
Type : string
Default value : 'E0047'
MISSING_AUTHENTICATION_TOKEN
Type : string
Default value : 'E0002'
PHONE_NUMBER_IS_INVALID
Type : string
Default value : 'E0021'
PHONE_NUMBER_IS_NEEDED
Type : string
Default value : 'E0020'
RETRIEVING_TIME_SLOTS_FAILED
Type : string
Default value : 'E0027'
SAVE_CONTACT_FAILED
Type : string
Default value : 'E0006'
SAVE_FILE_FAILED
Type : string
Default value : 'E0034'
SAVE_POSITIVE_INFO_FAILED
Type : string
Default value : 'E0046'
SAVE_PROFILE_FAILED
Type : string
Default value : 'E0005'
SAVE_TIME_SLOT_FAILED
Type : string
Default value : 'E0024'
SAVE_UNCONFIRMED_EMAIL_FAILED
Type : string
Default value : 'E0008'
SAVE_USER_FAILED
Type : string
Default value : 'E0013'
SEND_MAIL_FAILED
Type : string
Default value : 'E0012'
SEND_SMS_FAILED
Type : string
Default value : 'E0015'
TIME_SLOT_IS_UNAVAILABLE
Type : string
Default value : 'E0044'
TIME_SLOT_NOT_FOUND
Type : string
Default value : 'E0025'
UNCONFIRMED_EMAIL_NOT_FOUND
Type : string
Default value : 'E0009'
UNKNOWN_ERROR
Type : string
Default value : 'E0001'
UPDATE_CONTACT_FAILED
Type : string
Default value : 'E0014'
UPDATE_TIME_SLOT_FAILED
Type : string
Default value : 'E0028'
UPDATE_USER_DEVICE_ID_FAILED
Type : string
Default value : 'E0045'
UPDATE_USER_EMAIL_FAILED
Type : string
Default value : 'E0011'
USER_NOT_FOUND
Type : string
Default value : 'E0016'
VALIDATION_FAILED
Type : string
Default value : 'E0003'

test/mock/contact.repository.mock.ts

contactRepositoryMock
Type : object
Default value : { findContactsByUserId: jest.fn(async () => []), findManyByParams: jest.fn(async () => []), }

src/contact/provider/contact-repository.provider.ts

ContactRepositoryProvider
Type : object
Default value : { provide: ContactRepository, useFactory: (connection: Connection) => connection.getCustomRepository(ContactRepository), inject: [Connection], }

test/mock/contact.service.mock.ts

contactServiceMock
Type : object
Default value : { findActiveContactsByUserId: jest.fn(async () => ({})), }

src/common/helper/entity-encrypter.ts

decryptEntity
Default value : (entity: any, columns: string[]) => { columns.forEach((column: string) => { if (!falsyValues.includes(entity[column])) { entity[column] = Encrypter.decrypt(entity[column]); } }); }
encryptEntity
Default value : (entity: any, columns: string[]) => { columns.forEach((column: string) => { if (!falsyValues.includes(entity[column])) { entity[column] = Encrypter.encrypt(`${entity[column]}`); } }); }
falsyValues
Type : []
Default value : [undefined, null, '']

src/config/default.ts

env
Default value : process.env
firebaseAccountKey
Type : object
Default value : {}

src/config/typeorm.ts

env
Default value : process.env

test/mock/app.mock.ts

env
Default value : process.env
getTestApp
Default value : async () => { let app; const moduleFixture = await Test.createTestingModule({ imports: [AppModule] }) .overrideProvider(CognitoStrategy) .useValue({}) .overrideProvider(SchedulerService) .useValue({}) .overrideGuard(AuthGuard('cognito')) .useValue(authGuardMock) .overrideProvider(AWS.CognitoIdentityServiceProvider) .useValue(cognitoIdentityServiceMock) .overrideProvider(NOTIFICATION_DI.MAIL_JET) .useValue(mailJetMock) .overrideProvider(twilioLibrary.Twilio) .useValue(twilioMock) .overrideProvider(COMMON_DI.REDIS) .useValue(redisMock) .overrideProvider(COMMON_DI.CONFIG) .useValue(configMock) .overrideProvider(QUEUE.MESSAGE) .useValue(queueServiceMock) .overrideProvider(NOTIFICATION_DI.MAIL_JET) .useValue(mailJetMock) .overrideProvider(MESSAGE_DI.FIREBASE) .useValue(firebaseMock) .overrideProvider(FILE_DI.S3) .useValue(s3Mock) .overrideProvider(FILE_DI.CLOUD_FRONT_SIGNER) .useValue(cloudFrontSignerMock) .overrideProvider(FILE_DI.CLOUD_FRONT_SIGNER) .useValue(cloudFrontSignerMock) .overrideProvider(COMMON_DI.GOOGLE_PHONE_NUMBER) .useValue(googlePhoneNumberMock) .compile(); app = moduleFixture.createNestApplication(); app.useGlobalFilters(new ExceptionsFilter()); return app.init(); }

src/notification/helper/escape-html.ts

escapeHTML
Default value : (value: string): string => value.replace(/&/g, '&amp;').replace(/"/g, '&quot;')

test/mock/export.service.mock.ts

exportServiceMock
Type : object
Default value : {}

src/user/request/schema/export-user-data.schema.ts

exportUserDataSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ email: Joi.string().email().required(), })

src/user/request/schema/extended-profile.schema.ts

extendedProfileSchema
Type : object
Default value : { name: profileSchema.name.optional(), surname: profileSchema.surname.optional(), prefix: profileSchema.prefix, location: Joi.string().max(200), timezone: Joi.string().optional().allow('').max(200), phone: profileSchema.phone, email: Joi.string().email(), address: Joi.string().max(200), dateOfBirth: Joi.date().format("DD/MM/YYYY").max("now"), primaryPhysician: Joi.string(), primaryPhysicianAddress: Joi.string(), seriousMedicalIssues: Joi.boolean(), mostRecentDiagnosis: Joi.string().allow("", null), lastHospitalVisit: Joi.date().format("DD/MM/YYYY").allow(null).max("now"), allowNotifications: Joi.boolean(), tipsAndTricks: Joi.boolean(), emergencyEmailAndSms: Joi.boolean(), locationAccess: Joi.boolean(), uploadedDocumentsAccess: Joi.boolean(), readManual: Joi.boolean(), automatedEmergency: Joi.boolean(), emergencyMessage: Joi.string().min(10).max(1000), regularPushNotification: Joi.boolean(), frequencyOfRegularNotification: Joi.number().min(6).max(2880), positiveInfoPeriod: Joi.number().min(6).max(2880), pulseBasedTriggerIOSHealthPermissions: Joi.boolean(), pulseBasedTriggerIOSAppleWatchPaired: Joi.boolean(), pulseBasedTriggerGoogleFitAuthenticated: Joi.boolean(), pulseBasedTriggerConnectedToGoogleFit: Joi.boolean(), pulseBasedTriggerBackgroundModesEnabled: Joi.boolean(), }
Joi
Default value : JoiLibrary.extend(JoiDate)

test/mock/twilio.mock.ts

fetch
Default value : jest.fn(async () => ({}))
twilioMock
Type : object
Default value : { messages: { create: jest.fn(async () => ({ sid: uuid.v4(), errorCode: null })), }, }

test/mock/file-category.repository.mock.ts

fileCategoryRepositoryMock
Type : object
Default value : {}

src/file/provider/file-category-repository.provider.ts

FileCategoryRepositoryProvider
Type : object
Default value : { provide: FileCategoryRepository, useFactory: (connection: Connection) => connection.getCustomRepository(FileCategoryRepository), inject: [Connection], }

test/mock/file-category.service.mock.ts

fileCategoryServiceMock
Type : object
Default value : {}

test/mock/file.repository.mock.ts

fileRepositoryMock
Type : object
Default value : { findByCategoryCodeAndUserId: jest.fn(async () => []), findManyByParams: jest.fn(async () => []), }

src/file/provider/file-repository.provider.ts

FileRepositoryProvider
Type : object
Default value : { provide: FileRepository, useFactory: (connection: Connection) => connection.getCustomRepository(FileRepository), inject: [Connection], }

test/mock/file.service.mock.ts

fileServiceMock
Type : object
Default value : {}

src/file/mapper/files.mapper.ts

filesMapper
Default value : ( categories: FileCategoryEntity[], files: (FileEntity & { url: string })[] ): CategoryRO[] => categories.map((category) => plainToClass(CategoryRO, { ...category, files: files .filter((file) => file.categoryId === category.id) .map((file) => plainToClass(FileRO, file)), }) )

test/mock/firebase.mock.ts

firebaseMock
Type : object
Default value : {}

src/message/provider/firebase.provider.ts

FirebaseProvider
Type : object
Default value : { provide: DICTIONARY.FIREBASE, inject: [ConfigService], useFactory: (config: ConfigService) => { firebase.initializeApp({ credential: firebase.credential.cert(config.get('firebase.accountKey')), }); return firebase; }, }

src/authentication/request/schema/get-access-token.schema.ts

getAccessTokenSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ email: Joi.string().email(), password: Joi.string(), }).options({ presence: 'required', })

test/entity/category.mock.ts

getCategories
Default value : async (): Promise<FileCategoryEntity[]> => { return getConnection() .getRepository(FileCategoryEntity) .find({ order: { id: 'ASC', }, }); }

src/common/helper/get-enum-key-by-value.ts

getEnumKeyByValue
Default value : ( data: Record<string, string | number>, phrase: string | number, withLowerCase = true ): string => { let keyFound: string; for (const [key, value] of Object.entries(data)) { if (value === phrase) { keyFound = key; break; } } return withLowerCase ? keyFound.toLocaleLowerCase() : keyFound; }

src/common/helper/get-enum-keys.ts

getEnumKeys
Default value : ( data: Record<string, string | number>, withLowerCase = false ): string[] => { return Object.keys(data) .map((value) => (withLowerCase ? value.toLowerCase() : value)) .filter((value) => isNaN(parseInt(value))); }

test/entity/file.mock.ts

getFileById
Default value : async (id: number): Promise<FileEntity> => { return getConnection().getRepository(FileEntity).findOne(id); }
getFiles
Default value : async (id: number): Promise<FileEntity[]> => { return getConnection().getRepository(FileEntity).find(); }

src/common/helper/get-full-name.ts

getFullName
Default value : (name: string, surname: string): string => `${name || ''} ${surname || ''}`.trim()

src/notification/helper/get-template-id.ts

getMailTemplateId
Default value : (code: string): number => { return MailTemplatesConstants[LANGUAGE.ENGLISH][code]; }
MailTemplatesConstants
Type : object
Default value : {}

src/common/helper/get-name-or-email.ts

getNameOrEmail
Default value : ( name: string, surname: string, email: string ): string => { const fullName = getFullName(name, surname); return fullName !== '' ? fullName : email; }

test/entity/positive-info.mock.ts

getPositiveInfoByUserId
Default value : async ( userId: string ): Promise<PositiveInfoEntity> => { return getConnection() .getRepository(PositiveInfoEntity) .findOne({ where: { userId } }); }

src/user/helper/get-profile-default-values.ts

getProfileDefaultValues
Default value : ( profile: ProfileEntity ): Record<string, unknown> => ({ allowNotifications: profile?.allowNotifications !== false, tipsAndTricks: profile?.tipsAndTricks !== false, emergencyEmailAndSms: profile?.emergencyEmailAndSms !== false, uploadedDocumentsAccess: profile?.uploadedDocumentsAccess !== false, locationAccess: !!profile?.locationAccess, readManual: !!profile?.readManual, automatedEmergency: !!profile?.automatedEmergency, regularPushNotification: !!profile?.regularPushNotification, pulseBasedTriggerIOSHealthPermissions: !!profile?.pulseBasedTriggerIOSHealthPermissions, pulseBasedTriggerIOSAppleWatchPaired: !!profile?.pulseBasedTriggerIOSAppleWatchPaired, pulseBasedTriggerGoogleFitAuthenticated: !!profile?.pulseBasedTriggerGoogleFitAuthenticated, pulseBasedTriggerConnectedToGoogleFit: !!profile?.pulseBasedTriggerConnectedToGoogleFit, pulseBasedTriggerBackgroundModesEnabled: !!profile?.pulseBasedTriggerBackgroundModesEnabled, })

src/common/helper/get-time-from-date.ts

getTimeFromDate
Default value : (date: string): string => { return date ? date.slice(11,16) : null; }

test/entity/uncofirmed-email.mock.ts

getUnconfirmedEmailByUserId
Default value : async ( userId: string ): Promise<UnconfirmedEmailEntity> => { return getConnection() .getRepository(UnconfirmedEmailEntity) .findOne({ where: { userId } }); }

src/common/provider/google-phone-number.provider.ts

GoogleLibPhoneNumberProvider
Type : object
Default value : { provide: DICTIONARY.GOOGLE_PHONE_NUMBER, useFactory: () => { return LibPhoneNumber.PhoneNumberUtil.getInstance(); }, }

test/mock/google-phone-number.mock.ts

googlePhoneNumberMock
Type : object
Default value : { isValidNumber: jest.fn(() => true), parseAndKeepRawInput: jest.fn(() => ''), }

test/helper/contact.ts

initializeDataset
Default value : async (): Promise<{ users: UserEntity[]; contacts: ContactEntity[]; }> => { const users = await Promise.all([addUser(), addUser()]); const contacts = await Promise.all([ addContact({ userId: users[0].id, active: true, }), addContact({ userId: users[1].id, }), ]); return { users, contacts, }; }

test/helper/message.ts

initializeDataset
Default value : async (): Promise<{ user: UserEntity; contacts: ContactEntity[]; }> => { const user = await addUser(); user.profile = await addProfile({ userId: user.id, seriousMedicalIssues: false, mostRecentDiagnosis: null, lastHospitalVisit: null, emergencyEmailAndSms: true, locationAccess: true, automatedEmergency: false, readManual: false, location: faker.internet.url(), }); const contacts = await Promise.all([ addContact({ userId: user.id, active: true, }), addContact({ userId: user.id, active: false, }), ]); return { user, contacts, }; }

test/helper/user.ts

initializeDataset
Default value : async (): Promise<{ user: UserEntity; }> => { const user = await addUser(); user.profile = await addProfile({ userId: user.id, seriousMedicalIssues: false, mostRecentDiagnosis: null, lastHospitalVisit: null, emergencyEmailAndSms: true, locationAccess: true, automatedEmergency: false, }); return { user, }; }

src/common/helper/is-defined.ts

isDefined
Default value : (value: unknown): boolean => value !== null && value !== undefined

src/user/request/schema/update-user-profile-and-check-phone.schema.ts

Joi
Default value : JoiLibrary.extend(JoiDate)
updateUserProfileAndCheckPhoneSchema
Type : JoiLibrary.ObjectSchema
Default value : JoiLibrary.object({ ...extendedProfileSchema, countryCode: Joi.string(), }) .and('prefix', 'phone', 'countryCode') .options({ presence: 'optional', })

src/user/request/schema/update-user-profile.schema.ts

Joi
Default value : JoiLibrary.extend(JoiDate)
updateUserProfileSchema
Type : JoiLibrary.ObjectSchema
Default value : JoiLibrary.object({ ...extendedProfileSchema, }) .and('prefix', 'phone') .options({ presence: 'optional', })

test/mock/mailjet.mock.ts

mailJetMock
Type : object
Default value : { post: () => ({ request }), }
request
Default value : jest.fn(async () => ({ body: { Messages: [ { Status: 'success', }, ], }, }))

src/notification/provider/mail-jet.provider.ts

MailJetProvider
Type : object
Default value : { provide: DICTIONARY.MAIL_JET, inject: [ConfigService], useFactory: (config: ConfigService) => connect(config.get('mailJet.apiKey'), config.get('mailJet.apiSecret')), }

test/mock/message.service.mock.ts

messageServiceMock
Type : object
Default value : { addJobToQueue: jest.fn(async () => ({})), removeJobsByUserId: jest.fn(async () => ({})), }

src/common/helper/modify-time-according-timezone.ts

modifyTimeAccordingTimezone
Default value : (dateTime: string, timezone: string): string => { if (!timezone || timezone.length !== 6 || !["+", "-"].includes(timezone[0]) || timezone[3] !== ':') { return moment(dateTime).format('DD.MM.YYYY HH:mm:ss'); } const operation = timezone[0]; const [hours, minutes] = timezone.slice(1, 6).split(':'); const convertedHours = parseInt(hours); const convertedMinutes = parseInt(minutes); let convertedDateTime = moment(dateTime); if (operation === '+') { convertedDateTime = convertedDateTime .add(convertedHours, 'hour') .add(convertedMinutes, 'minute'); } if (operation === '-') { convertedDateTime = convertedDateTime .subtract(convertedHours, 'hour') .subtract(convertedMinutes, 'minute'); } return convertedDateTime.format('DD.MM.YYYY HH:mm:ss'); }

src/user/request/schema/note-positive-info.schema.ts

notePositiveInfoSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ minutesToNext: Joi.number().min(6).max(2880), }).options({ presence: "optional", })

test/mock/notification.service.mock.ts

notificationServiceMock
Type : object
Default value : { prepareEmailData: jest.fn(() => ({})), prepareSmsData: jest.fn(() => ({})), sendEmergencyMessage: jest.fn(async () => ({})), sendSms: jest.fn(async () => ({})), sendEmail: jest.fn(async () => ({})), }

src/trigger-time-slot/enum/days-of-week.enum.ts

numberToDaysOfWeek
Default value : new Map([ [2, 'Monday'], [3, 'Tuesday'], [4, 'Wednesday'], [5, 'Thursday'], [6, 'Friday'], [7, 'Saturday'], [1, 'Sunday'], ])

src/common/helper/omit.ts

omit
Default value : ( obj: | Record<string, unknown> | UpdateUserProfileDTO | UpdateContactAndCheckPhoneDTO | AddContactAndCheckPhoneDTO | AddTimeSlotDTO | UserEntity | ProfileEntity | ContactEntity | TimeSlotEntity | TimeSlotDayEntity | UnconfirmedEmailEntity | FileEntity, omittedKeys: string[] ): any => Object.entries(obj) .filter(([key]) => !omittedKeys.includes(key)) .reduce((newObj, [key, val]) => Object.assign(newObj, { [key]: val }), {})

test/mock/positive-info.repository.mock.ts

positiveInfoRepositoryMock
Type : object
Default value : {}

src/user/provider/positive-info-repository.provider.ts

PositiveInfoRepositoryProvider
Type : object
Default value : { provide: PositiveInfoRepository, useFactory: (connection: Connection) => connection.getCustomRepository(PositiveInfoRepository), inject: [Connection], }

test/mock/positive-info.service.mock.ts

positiveInfoServiceMock
Type : object
Default value : { savePositiveInfo: jest.fn() }

src/user/mapper/profile.mapper.ts

profileMapper
Default value : (profile: ProfileEntity): ProfileRO => { return plainToClass(ProfileRO, { ...profile, ...getProfileDefaultValues(profile), }); }

test/mock/profile.repository.mock.ts

profileRepositoryMock
Type : object
Default value : {}

src/user/provider/profile-repository.provider.ts

ProfileRepositoryProvider
Type : object
Default value : { provide: ProfileRepository, useFactory: (connection: Connection) => connection.getCustomRepository(ProfileRepository), inject: [Connection], }

src/common/request/schema/profile.schema.ts

profileSchema
Type : object
Default value : { name: Joi.string().max(100).required(), surname: Joi.string().max(100).required(), active: Joi.boolean().allow(null), prefix: Joi.number().min(1).max(999).allow(null), phone: Joi.string().allow(null).min(4).max(12).regex(/^\d+$/), email: Joi.string() .email() .max(320) .allow(null) .when('phone', { is: null, then: Joi.string() }), }

test/mock/profile.service.mock.ts

profileServiceMock
Type : object
Default value : { findByUserId: jest.fn(async () => ({})), saveProfile: jest.fn(async () => ({})), }

src/queue/provider/message-queue.provider.ts

QueueMessageProvider
Type : FactoryProvider<any>
Default value : { provide: QUEUE.MESSAGE, inject: [ConfigService], useFactory: (config: ConfigService) => Queue(QUEUE.MESSAGE, { redis: { password: config.get('redis.password'), port: config.get('redis.port'), host: config.get('redis.host'), tls: config.get('redis.disableTls') ? undefined : { servername: config.get('redis.host'), rejectUnauthorized: false, }, }, defaultJobOptions: { removeOnComplete: true, attempts: config.get('queue.numberOfAttempts'), }, }), }

test/mock/queue.service.mock.ts

queueServiceMock
Type : object
Default value : { add: jest.fn(async () => ({})), removeJobs: jest.fn(async () => ({})), getJob: jest.fn(async () => ({})), }

test/mock/redis.mock.ts

redisMock
Default value : new Redis({ data: {}, })

src/common/provider/redis.provider.ts

RedisProvider
Type : FactoryProvider<any>
Default value : { provide: DICTIONARY.REDIS, inject: [ConfigService], useFactory: (config: ConfigService) => new Redis(config.get('redis')), }

src/authentication/decorator/roles.decorator.ts

Roles
Default value : (args: number[]) => SetMetadata('roles', args)

test/mock/s3.mock.ts

s3Mock
Type : object
Default value : { upload: jest.fn((params, cb) => cb(undefined, { Key: faker.datatype.uuid() }) ), deleteObject: jest.fn((params, cb) => cb(undefined, {})), copyObject: jest.fn((params, cb) => cb(undefined, {})), getSignedUrl: jest.fn(async () => faker.image.imageUrl()), getObject: jest.fn((params, cb) => cb(undefined, { Body: faker.datatype.string() }) ), }

src/message/request/schema/send-emergency-message.schema.ts

sendEmergencyMessageSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ delayed: Joi.boolean(), messageType: Joi.string() .valid(...Object.values(MESSAGE_TYPE)) .when("delayed", { is: Joi.exist().valid(true), then: Joi.required(), otherwise: Joi.optional(), }), }).options({ presence: "optional", })

src/message/request/schema/send-sms.schema.ts

sendSmsSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ messageType: Joi.string() .valid(...Object.values(MESSAGE_TYPE)) .required(), })

test/mock/time-slot-day.repository.mock.ts

timeSlotDayRepositoryMock
Type : object
Default value : {}

src/trigger-time-slot/provider/time-slot-day-repository.provider.ts

TimeSlotDayRepositoryProvider
Type : object
Default value : { provide: TimeSlotDayRepository, useFactory: (connection: Connection) => connection.getCustomRepository(TimeSlotDayRepository), inject: [Connection], }

src/trigger-time-slot/mapper/time-slot.mapper.ts

timeSlotMapper
Default value : (timeSlot: TimeSlotEntity): TimeSlotRO => plainToClass(TimeSlotRO, { ...timeSlot, days: timeSlot.days.map((item) => getEnumKeyByValue(DAYS_OF_WEEKS, item.day) ), })

test/mock/time-slot.repository.mock.ts

timeSlotRepositoryMock
Type : object
Default value : {}

src/trigger-time-slot/provider/time-slot-repository.provider.ts

TimeSlotRepositoryProvider
Type : object
Default value : { provide: TimeSlotRepository, useFactory: (connection: Connection) => connection.getCustomRepository(TimeSlotRepository), inject: [Connection], }

src/trigger-time-slot/request/schema/time-slot.schema.ts

timeSlotSchema
Type : object
Default value : { active: Joi.boolean(), from: Joi.date().iso().allow(null), to: Joi.date().iso().required(), timezone: Joi.string().required(), days: Joi.array() .items( Joi.string() .valid(...getEnumKeys(DAYS_OF_WEEKS, true)) .required() ) .required(), }

src/trigger-time-slot/mapper/time-slots.mapper.ts

timeSlotsMapper
Default value : (timeSlots: TimeSlotEntity[]): TimeSlotRO[] => timeSlots.map((entity) => timeSlotMapper(entity))

test/mock/trigger-time-slot.service.mock.ts

triggerTimeSlotServiceMock
Type : object
Default value : { isActiveTimeSlot: jest.fn(async () => true), getActiveTimeSlot: jest.fn(async () => null), }

src/notification/provider/twilio.provider.ts

TwilioProvider
Type : object
Default value : { provide: twilio.Twilio, inject: [ConfigService], useFactory: (config: ConfigService) => twilio(config.get('twilio.accountSid'), config.get('twilio.authToken')), }

test/mock/unconfirmed-email.repository.mock.ts

unconfirmedEmailRepositoryMock
Type : object
Default value : {}

src/user/provider/unconfirmed-email-repository.provider.ts

UnconfirmedEmailRepositoryProvider
Type : object
Default value : { provide: UnconfirmedEmailRepository, useFactory: (connection: Connection) => connection.getCustomRepository(UnconfirmedEmailRepository), inject: [Connection], }

test/mock/unconfirmed-email.service.mock.ts

unconfirmedEmailServiceMock
Type : object
Default value : { saveUnconfirmedEmail: jest.fn(async () => ({})), }

src/contact/request/schema/update-contact-and-check-phone.schema.ts

updateContactAndCheckPhoneSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ name: profileSchema.name.optional(), surname: profileSchema.surname.optional(), active: profileSchema.active, prefix: profileSchema.prefix, phone: profileSchema.phone, email: profileSchema.email, countryCode: Joi.string(), }) .and('prefix', 'phone', 'countryCode') .options({ presence: 'optional', })

src/contact/request/schema/update-contact.schema.ts

updateContactSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ name: profileSchema.name.optional(), surname: profileSchema.surname.optional(), active: profileSchema.active, prefix: profileSchema.prefix, phone: profileSchema.phone, email: profileSchema.email, }) .and('prefix', 'phone') .options({ presence: 'optional', })

src/trigger-time-slot/request/schema/update-time-slot.schema.ts

updateTimeSlotSchema
Type : Joi.ObjectSchema
Default value : Joi.object( timeSlotSchema ).options({ presence: 'optional', })

src/user/request/schema/update-user-device-id.schema.ts

updateUserDeviceIdSchema
Type : Joi.ObjectSchema
Default value : Joi.object({ deviceId: Joi.string().max(200).allow(null).required(), })

src/authentication/decorator/user.decorator.ts

User
Default value : createParamDecorator((data, ctx: ExecutionContext) => { const request = ctx.switchToHttp().getRequest(); return request.user; })

test/mock/user.repository.mock.ts

userRepositoryMock
Type : object
Default value : {}

src/user/provider/user-repository.provider.ts

UserRepositoryProvider
Type : object
Default value : { provide: UserRepository, useFactory: (connection: Connection) => connection.getCustomRepository(UserRepository), inject: [Connection], }

test/mock/user.service.mock.ts

userServiceMock
Type : object
Default value : { findByIdOrFail: jest.fn(async () => ({})), updateUserDeviceId: jest.fn(), clearPositiveInfo: jest.fn() }

results matching ""

    No results matching ""