Skip to content

Commit

Permalink
refactor(sms_count): sms service wraps model count documents call
Browse files Browse the repository at this point in the history
  • Loading branch information
seaerchin committed Jul 1, 2021
1 parent e32cd09 commit 766ca02
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 10 deletions.
6 changes: 1 addition & 5 deletions src/app/services/sms/sms.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { StatusCodes } from 'http-status-codes'
import { Types } from 'mongoose'

import { ErrorDto } from '../../../types/api'
import { createLoggerWithLabel } from '../../config/logger'
Expand Down Expand Up @@ -40,10 +39,7 @@ export const _handleGetFreeSmsCountForFormAdmin: ControllerHandler<
FormService.retrieveFormById(formId)
// Step 2: Retrieve the free sms count
.andThen(({ msgSrvcName, admin }) => {
// This casting is required because no type parameter is specified on the document.
// Hence, this defaults to any but on the schema, this is defined as an ObjectId
const adminId = (admin as Types.ObjectId).toHexString()
return SmsService.retrieveFreeSmsCounts(adminId).map(
return SmsService.retrieveFreeSmsCounts(String(admin)).map(
(freeSmsCount) => ({
msgSrvcSid: msgSrvcName,
freeSmsCount,
Expand Down
6 changes: 1 addition & 5 deletions src/app/services/sms/sms.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,11 +476,7 @@ export const retrieveFreeSmsCounts = (
userId: string,
): ResultAsync<number, PossibleDatabaseError> => {
return ResultAsync.fromPromise(
SmsCount.countDocuments({
'formAdmin.userId': userId,
smsType: SmsType.Verification,
isOnboardedAccount: false,
}).exec(),
SmsCount.retrieveFreeSmsCounts(userId),
(error) => {
logger.error({
message: `Retrieving free sms counts failed for ${userId}`,
Expand Down
1 change: 1 addition & 0 deletions src/app/services/sms/sms.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export interface IBouncedSubmissionSmsCountSchema

export interface ISmsCountModel extends Model<ISmsCountSchema> {
logSms: (logParams: LogSmsParams) => Promise<ISmsCountSchema>
retrieveFreeSmsCounts: (userId: string) => Promise<number>
}

export type TwilioCredentials = {
Expand Down
10 changes: 10 additions & 0 deletions src/app/services/sms/sms_count.server.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,16 @@ const compileSmsCountModel = (db: Mongoose) => {
return smsCount.save()
}

SmsCountSchema.statics.retrieveFreeSmsCounts = async function (
userId: string,
) {
return this.countDocuments({
'formAdmin.userId': userId,
smsType: SmsType.Verification,
isOnboardedAccount: false,
}).exec()
}

const SmsCountModel = db.model<ISmsCountSchema, ISmsCountModel>(
SMS_COUNT_SCHEMA_NAME,
SmsCountSchema,
Expand Down

0 comments on commit 766ca02

Please sign in to comment.