Skip to content

Commit

Permalink
refactor: migrate admin-console client service to ts (#1531)
Browse files Browse the repository at this point in the history
* feat(public/services/billingservice): added billing service

* feat(public/services/exampleservice): added example service

* test(public/services/billingservice): adds tests for getBillingInfo

* test(public/services/exampleservice): adds tests for getSingleExampleForm and getExampleForms

* refactor(billingservice): added dto types to fe/be and type annnotation on get for fe

* style(public/exampleservice): added curly braces; added type annotation on methods

* refactor(examples): adds dto to params and updated fe file naming to fit be

* test(examplesservice): updated tests to use new dto shape

* refactor(billing): updated billing fe/be to use dto

* test(billingservice): updated tests to use dto for params

* refactor(examples-list/controller): updated to use ExamplesService

* refactor(billing/client/controller): replaced AdminService  with new BillingService

* refactor(forms/client/routes): replaced AdminConsole with ExamplesService

* chore(main.js): deletes old admin-console.client.service

* test(billingservice): updated test blocks

* test(exampleservice): updated test blocks

* style(types/billing): imported LoginStatistic rather than redefining
  • Loading branch information
seaerchin authored Apr 7, 2021
1 parent 1c6bc68 commit 324a510
Show file tree
Hide file tree
Showing 16 changed files with 291 additions and 108 deletions.
4 changes: 3 additions & 1 deletion src/app/modules/billing/__tests__/billing.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ describe('billing.controller', () => {
...EXPECTED_SERVICE_CALL_ARGS,
)
expect(mockRes.status).toBeCalledWith(500)
expect(mockRes.json).toBeCalledWith('Error in retrieving billing records')
expect(mockRes.json).toBeCalledWith({
message: 'Error in retrieving billing records',
})
})
})
})
4 changes: 3 additions & 1 deletion src/app/modules/billing/__tests__/billing.routes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,9 @@ describe('billing.routes', () => {
// Assert
expect(retrieveStatsSpy).toBeCalled()
expect(response.status).toEqual(500)
expect(response.body).toEqual('Error in retrieving billing records')
expect(response.body).toEqual({
message: 'Error in retrieving billing records',
})
})
})
})
Expand Down
11 changes: 4 additions & 7 deletions src/app/modules/billing/billing.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { StatusCodes } from 'http-status-codes'
import moment from 'moment-timezone'

import { createLoggerWithLabel } from '../../../config/logger'
import { BillingInfoDto, BillingQueryDto, ErrorDto } from '../../../types/api'
import { createReqMeta } from '../../utils/request'

import { BillingFactory } from './billing.factory'
Expand All @@ -20,13 +21,9 @@ const logger = createLoggerWithLabel(module)
*/
export const handleGetBillInfo: RequestHandler<
ParamsDictionary,
ErrorDto | BillingInfoDto,
unknown,
unknown,
{
esrvcId: string
yr: string
mth: string
}
BillingQueryDto
> = async (req, res) => {
const { esrvcId, mth, yr } = req.query
const authedUser = (req.session as Express.AuthedSession).user
Expand Down Expand Up @@ -54,7 +51,7 @@ export const handleGetBillInfo: RequestHandler<
})
return res
.status(StatusCodes.INTERNAL_SERVER_ERROR)
.json('Error in retrieving billing records')
.json({ message: 'Error in retrieving billing records' })
}

// Retrieved login stats successfully.
Expand Down
20 changes: 14 additions & 6 deletions src/app/modules/examples/examples.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,32 @@ import { ParamsDictionary, Query } from 'express-serve-static-core'
import { StatusCodes } from 'http-status-codes'

import { createLoggerWithLabel } from '../../../config/logger'
import {
ErrorDto,
ExampleFormsQueryDto,
ExampleFormsResult,
ExampleSingleFormResult,
} from '../../../types/api'
import { createReqMeta } from '../../utils/request'

import { ExamplesFactory } from './examples.factory'
import { ExamplesQueryParams } from './examples.types'
import { mapRouteError } from './examples.utils'

const logger = createLoggerWithLabel(module)

/**
* Handler for GET /examples endpoint.
* @security session
* @param exampleFormsQuery The search terms to find forms for
* @returns 200 with an array of forms to be listed on the examples page
* @returns 401 when user does not exist in session
* @returns 500 when error occurs whilst querying the database
*/
export const handleGetExamples: RequestHandler<
ParamsDictionary,
ErrorDto | ExampleFormsResult,
unknown,
unknown,
Query & ExamplesQueryParams
Query & ExampleFormsQueryDto
> = (req, res) => {
return ExamplesFactory.getExampleForms(req.query)
.map((result) => res.status(StatusCodes.OK).json(result))
Expand All @@ -44,14 +50,16 @@ export const handleGetExamples: RequestHandler<
/**
* Handler for GET /examples/:formId endpoint.
* @security session
* @param formId The id of the example form
* @returns 200 with the retrieved form example
* @returns 401 when user does not exist in session
* @returns 404 when the form with given formId does not exist in the database
* @returns 500 when error occurs whilst querying the database
*/
export const handleGetExampleByFormId: RequestHandler<{
formId: string
}> = (req, res) => {
export const handleGetExampleByFormId: RequestHandler<
{ formId: string },
ExampleSingleFormResult | ErrorDto
> = (req, res) => {
const { formId } = req.params

return ExamplesFactory.getSingleExampleForm(formId)
Expand Down
1 change: 0 additions & 1 deletion src/public/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,6 @@ require('./modules/users/config/users.client.routes.js')

// User services
require('./modules/users/services/auth.client.service.js')
require('./modules/users/services/admin-console.client.service.js')

// User controllers
require('./modules/users/controllers/authentication.client.controller.js')
Expand Down
10 changes: 6 additions & 4 deletions src/public/modules/forms/config/forms.client.routes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict'

const ExamplesService = require('../../../services/ExamplesService')

// Setting up route
angular.module('forms').config([
'$stateProvider',
Expand Down Expand Up @@ -72,22 +74,22 @@ angular.module('forms').config([
url: '/{formId:[0-9a-fA-F]{24}}/use-template',
templateUrl: 'modules/users/views/examples.client.view.html',
resolve: {
AdminConsole: 'AdminConsole',
Auth: 'Auth',
FormErrorService: 'FormErrorService',
// If the user is logged in, this field will contain the form data of the provided formId,
// otherwise it will only contain the formId itself.
FormData: [
'AdminConsole',
'$q',
'Auth',
'FormErrorService',
'$stateParams',
function (AdminConsole, Auth, FormErrorService, $stateParams) {
function ($q, Auth, FormErrorService, $stateParams) {
if (!Auth.getUser()) {
return $stateParams.formId
}

return AdminConsole.getSingleExampleForm($stateParams.formId)
return $q
.when(ExamplesService.getSingleExampleForm($stateParams.formId))
.then(function (response) {
response.form.isTemplate = true
return response.form
Expand Down
21 changes: 9 additions & 12 deletions src/public/modules/users/controllers/billing.client.controller.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
'use strict'

const CsvGenerator = require('../../forms/helpers/CsvGenerator')
const BillingService = require('../../../services/BillingService')

angular
.module('users')
.controller('BillingController', [
'$q',
'$state',
'$timeout',
'AdminConsole',
'Auth',
'NgTableParams',
BillingController,
])

function BillingController(
$state,
$timeout,
AdminConsole,
Auth,
NgTableParams,
) {
function BillingController($q, $state, $timeout, Auth, NgTableParams) {
const vm = this

vm.user = Auth.getUser()
Expand Down Expand Up @@ -102,10 +97,12 @@ function BillingController(
esrvcId = esrvcId || vm.esrvcId
vm.loading = true
vm.searchError = false
AdminConsole.getBillingInfo(
vm.selectedTimePeriod.yr,
vm.selectedTimePeriod.mth,
esrvcId,
$q.when(
BillingService.getBillingInfo({
yr: vm.selectedTimePeriod.yr,
mth: vm.selectedTimePeriod.mth,
esrvcId,
}),
).then(
function (response) {
// Remove loader
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use strict'

const ExamplesService = require('../../../services/ExamplesService')

const PAGE_SIZE = 16

angular.module('users').controller('ExamplesController', [
'$q',
'$scope',
'AdminConsole',
'Auth',
'GTag',
'$state',
Expand All @@ -17,8 +19,8 @@ angular.module('users').controller('ExamplesController', [
])

function ExamplesController(
$q,
$scope,
AdminConsole,
Auth,
GTag,
$state,
Expand Down Expand Up @@ -129,12 +131,14 @@ function ExamplesController(
const shouldGetTotalNumResults = pageNo === 0 && searchTerm !== ''

// Get next page of forms and add to ui
AdminConsole.getExampleForms({
pageNo,
searchTerm,
agency,
shouldGetTotalNumResults,
}).then(
$q.when(
ExamplesService.getExampleForms({
pageNo,
searchTerm,
agency,
shouldGetTotalNumResults,
}),
).then(
function (response) {
/* Form Properties
------------------
Expand Down
68 changes: 0 additions & 68 deletions src/public/modules/users/services/admin-console.client.service.js

This file was deleted.

21 changes: 21 additions & 0 deletions src/public/services/BillingService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import axios from 'axios'

import { BillingInfoDto, BillingQueryDto } from '../../types/api/billing'

// Exported for testing
export const BILLING_ENDPOINT = '/billing'

/**
* Gets the billing information for the given month and year
* @param billingQueryParams The formId and the specific month to get the information for
* @returns Promise<BillingResult> The billing statistics of the given month
*/
export const getBillingInfo = (
billingQueryParams: BillingQueryDto,
): Promise<BillingInfoDto> => {
return axios
.get<BillingInfoDto>(BILLING_ENDPOINT, {
params: billingQueryParams,
})
.then(({ data }) => data)
}
42 changes: 42 additions & 0 deletions src/public/services/ExamplesService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import axios from 'axios'

import {
ExampleFormsQueryDto,
ExampleFormsResult,
ExampleSingleFormResult,
} from '../../types/api'

export const EXAMPLES_ENDPOINT = '/examples'

/**
* Gets example forms that matches the specified parameters for listing
* @param exampleFormsSearchParams The search terms to query the backend for
* @returns The list of retrieved examples if `shouldGetTotalNumResults` is false
* @returns The list of retrieved examples with the total results if `shouldGetTotalNumResults` is true
*/
export const getExampleForms = (
exampleFormsSearchParams: ExampleFormsQueryDto,
): Promise<ExampleFormsResult> => {
return axios
.get<ExampleFormsResult>(EXAMPLES_ENDPOINT, {
params: exampleFormsSearchParams,
// disable IE ajax request caching (so search requests don't get cached)
headers: { 'If-Modified-Since': '0' },
})
.then(({ data }) => data)
}
/**
* Gets a single form for examples
* @param formId The id of the form to search for
* @returns The information of the example form
*/
export const getSingleExampleForm = (
formId: string,
): Promise<ExampleSingleFormResult> => {
return axios
.get<ExampleSingleFormResult>(`${EXAMPLES_ENDPOINT}/${formId}`, {
// disable IE ajax request caching (so search requests don't get cached)
headers: { 'If-Modified-Since': '0' },
})
.then(({ data }) => data)
}
Loading

0 comments on commit 324a510

Please sign in to comment.