Skip to content

Commit

Permalink
feat: #1039 update insomania, cloud-alert to match the new api schema
Browse files Browse the repository at this point in the history
  • Loading branch information
undefined committed Jun 18, 2020
1 parent 2623ced commit 7735943
Show file tree
Hide file tree
Showing 12 changed files with 227 additions and 54 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ if (Cypress.env('PACKAGE_NAME') === 'all' || Cypress.env('PACKAGE_NAME') === 'we
})
})
})
it('user should able to call web-components-config-server /v1/web-components-config/<customer_id>', () => {
it('user should able to call web-components-config-server /v1/web-components-config/<customer_id>/<app_id>', () => {
cy.request({
url: `${WEB_COMPONENTS_CONFIG_API_URL}/v1/web-components-config/ZZA`,
url: `${WEB_COMPONENTS_CONFIG_API_URL}/v1/web-components-config/TEST/1`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { validateGetById, validateCreate, validateUpdate, validateDelete, validateFollowSchema } from '../validators'
import { validateGetById, validateCreate, validatePatch, validateDelete, validateFollowSchema } from '../validators'

describe('validateGetById', () => {
it('should return correctly', () => {
Expand Down Expand Up @@ -95,9 +95,9 @@ describe('validateCreate', () => {
})
})

describe('validateUpdate', () => {
describe('validatePatch', () => {
it('should return correctly', () => {
const result = validateUpdate({ customerId: 'id1', appId: 'id1', appointmentLength: 20 })
const result = validatePatch({ customerId: 'id1', appId: 'id1', appointmentLength: 20 })
expect(result).toBe(true)
})

Expand All @@ -106,7 +106,7 @@ describe('validateUpdate', () => {
error.message = 'Invalid params'
error.code = '400'
expect(() => {
validateUpdate({ customerIdFake: 'id1', appointmentLength: 20 })
validatePatch({ customerIdFake: 'id1', appointmentLength: 20 })
}).toThrowError(error)
})

Expand All @@ -115,7 +115,7 @@ describe('validateUpdate', () => {
error.message = 'Invalid params'
error.code = '400'
expect(() => {
validateUpdate({ customerId: 'id1', invalidParam: 'param' })
validatePatch({ customerId: 'id1', invalidParam: 'param' })
}).toThrowError(error)
})

Expand All @@ -124,7 +124,7 @@ describe('validateUpdate', () => {
error.message = 'Invalid daysOfWeek.'
error.code = '400'
expect(() => {
validateUpdate({ customerId: 'id1', appId: 'id1', appointmentLength: 20, daysOfWeek: [9] })
validatePatch({ customerId: 'id1', appId: 'id1', appointmentLength: 20, daysOfWeek: [9] })
}).toThrowError(error)
})
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,104 @@ import {
webComponentsConfigGetByIdHandler,
webComponentsConfigPatchHandler,
webComponentsConfigDeleteHandler,
webComponentsConfigPutHandler,
webComponentsConfigPostHandler,
} from '../web-components-config'
import { webComponentConfig } from '../__mocks__/web-components-config'

jest.mock('../api', () => {
return {
getConfigByClientId: jest.fn(() => Promise.resolve(webComponentConfig)),
createConfig: jest.fn(() => Promise.resolve(webComponentConfig)),
updateConfig: jest.fn(() => Promise.resolve(webComponentConfig)),
patchConfig: jest.fn(() => Promise.resolve(webComponentConfig)),
deleteConfig: jest.fn(() => Promise.resolve(webComponentConfig)),
putConfig: jest.fn(() => Promise.resolve(webComponentConfig)),
}
})

describe('web-components-config', () => {
describe('webComponentsConfigPutHandler', () => {
it('should update correctly and return service is running', async done => {
const mockRequest = ({
traceId: 'mockTraceId',
headers: {},
body: {
customerId: 'DXX',
appId: '1',
appointmentLength: 1,
daysOfWeek: [1],
appointmentTimeGap: 5,
appointmentTypes: [],
negotiatorIds: [],
},
params: {
clientId: '1',
appId: '1',
traceId: 'mockUUID',
},
} as unknown) as AppRequest
const mockResponse = ({
send: jest.fn().mockReturnValue({}),
status: jest.fn().mockReturnValue(200),
sendStatus: jest.fn().mockReturnValue(200),
json: jest.fn().mockReturnValue({}),
} as unknown) as AppResponse
await webComponentsConfigPutHandler(mockRequest, mockResponse)
setTimeout(() => {
expect(mockResponse.send).toBeCalledWith(webComponentConfig)
done()
}, 1000)
})
})

describe('webComponentsConfigPostHandler', () => {
it('should run correctly and return service is running', async done => {
const mockRequest = ({
traceId: 'mockTraceId',
headers: {},
body: {
customerId: 'DXX',
appId: '1',
appointmentLength: 303,
appointmentTimeGap: 5,
appointmentTypes: [
{
M: {
value: {
S: 'value1',
},
id: {
S: 'id1',
},
},
},
],
negotiatorIds: [
{
S: 'AAAN',
},
],
daysOfWeek: [],
},
params: {
clientId: '1',
traceId: 'mockUUID',
},
} as unknown) as AppRequest
const mockResponse = ({
send: jest.fn().mockReturnValue({}),
status: jest.fn().mockReturnValue(200),
sendStatus: jest.fn().mockReturnValue(200),
json: jest.fn().mockReturnValue({}),
} as unknown) as AppResponse
await webComponentsConfigPostHandler(mockRequest, mockResponse)
setTimeout(() => {
expect(mockResponse.send).toBeCalledWith(webComponentConfig)
done()
}, 1000)
})
})

describe('webComponentsConfigGetByIdHandler', () => {
it('should run correctly and return service is running', async done => {
const mockRequest = ({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import dynamoDBMapper from '@/dynamodb-mapper'
import { FunctionExpression, AttributePath } from '@aws/dynamodb-expressions'
import logger from '@/logger'
import { CreateParams, DeleteParams, UpdateParams, GetByClientIdParams } from '@/schemas/api-types'
import { WebComponentConfig } from '@/schemas/schema'
Expand All @@ -20,10 +21,16 @@ export const getConfigByClientId = async ({ traceId, data }: GetByClientIdParams

export const createConfig = async ({ traceId, data }: CreateParams): Promise<WebComponentConfig> => {
try {
logger.info('Creating config...', { traceId, data })

const itemToCreate = generateSchemaItem(data)
const result = await dynamoDBMapper.put(itemToCreate)
const result = await dynamoDBMapper.put(itemToCreate, {
condition: {
type: 'And',
conditions: [
new FunctionExpression('attribute_not_exists', new AttributePath('customerId')),
new FunctionExpression('attribute_not_exists', new AttributePath('appId')),
],
},
})
logger.info('Create config successfully', { traceId, result })
return result
} catch (error) {
Expand All @@ -32,13 +39,26 @@ export const createConfig = async ({ traceId, data }: CreateParams): Promise<Web
}
}

export const updateConfig = async ({ traceId, data }: UpdateParams): Promise<WebComponentConfig> => {
export const patchConfig = async ({ traceId, data }: UpdateParams): Promise<WebComponentConfig> => {
try {
logger.info('Updating config...', { traceId, data })
const { customerId, ...rest } = data
const oldItem = await getConfigByClientId({ traceId, data: { customerId } })
logger.info('Patching config...', { traceId, data })
const { customerId, appId, ...rest } = data
const oldItem = await getConfigByClientId({ traceId, data: { customerId, appId } })
const itemToUpdate = generateSchemaItem({ ...oldItem, ...rest })
const result = await dynamoDBMapper.update(itemToUpdate)
logger.info('Patch config successfully', { traceId, result })
return result
} catch (error) {
await logger.error('Patch config failed', { traceId, error: stringifyError(error) })
throw error
}
}

export const putConfig = async ({ traceId, data }): Promise<WebComponentConfig> => {
try {
logger.info('Updating config...', { traceId, data })
const itemToUpdate = generateSchemaItem(data)
const result = await dynamoDBMapper.put(itemToUpdate)
logger.info('Update config successfully', { traceId, result })
return result
} catch (error) {
Expand All @@ -50,7 +70,7 @@ export const updateConfig = async ({ traceId, data }: UpdateParams): Promise<Web
export const deleteConfig = async ({ traceId, data }: DeleteParams): Promise<WebComponentConfig> => {
try {
logger.info('Deleting config...', { traceId, data })
const itemToDelete = generateSchemaItem({ appId: data.customerId })
const itemToDelete = generateSchemaItem(data)
const result = await dynamoDBMapper.delete(itemToDelete)
logger.info('Delete config successfully', { traceId, result })
return result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const CREATE_REQUIRED_PARAMS = [
'negotiatorIds',
'daysOfWeek',
]
export const UPDATE_REQUIRED_PARAMS = ['customerId', 'appId']
export const PATCH_REQUIRED_PARAMS = ['customerId', 'appId']
export const DELETE_REQUIRED_PARAMS = ['customerId', 'appId']

/**
Expand Down Expand Up @@ -72,6 +72,7 @@ export const validateGetById = (data: { [key: string]: any }) => {

export const validateCreate = (data: { [key: string]: any }) => {
const dataKeys = Object.keys(data)
console.log(dataKeys)

// check if param keys are valid
const isParamsValid =
Expand All @@ -95,12 +96,12 @@ export const validateCreate = (data: { [key: string]: any }) => {
return true
}

export const validateUpdate = (data: { [key: string]: any }) => {
export const validatePatch = (data: { [key: string]: any }) => {
const dataKeys = Object.keys(data)

// check if param keys are valid
const isParamsValid =
dataKeys.some(key => UPDATE_REQUIRED_PARAMS.includes(key)) && dataKeys.every(key => ALL_PARAMS.includes(key))
dataKeys.some(key => CREATE_REQUIRED_PARAMS.includes(key)) && dataKeys.every(key => ALL_PARAMS.includes(key))
// check if param is a valid schema item
const errorMessage = validateFollowSchema(data)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import express from 'express'
import { getConfigByClientId, createConfig, deleteConfig, updateConfig } from './api'
import { getConfigByClientId, createConfig, deleteConfig, patchConfig, putConfig } from './api'
import { AppRequest, AppResponse } from '@/app'
import logger from '@/logger'
import { validateGetById, validateCreate, validateUpdate, validateDelete } from './validators'
import { validateGetById, validateCreate, validatePatch, validateDelete } from './validators'
import { stringifyError } from '@reapit/node-utils'

const webComponentsConfig = express.Router()

export const webComponentsConfigGetByIdHandler = async (req: AppRequest, res: AppResponse) => {
try {
const params = {
data: { customerId: req.params.customerId },
data: { customerId: req.params.customerId, appId: req.params.appId },
traceId: req.traceId,
}
const { data } = params

validateGetById(data)
const result = await getConfigByClientId(params)
return res.send(result)
Expand All @@ -30,12 +31,12 @@ export const webComponentsConfigGetByIdHandler = async (req: AppRequest, res: Ap
export const webComponentsConfigPatchHandler = async (req: AppRequest, res: AppResponse) => {
try {
const params = {
data: { customerId: req.params.customerId, appId: req.params.appId, ...req.body },
data: { ...req.body, customerId: req.params.customerId, appId: req.params.appId },
traceId: req.traceId,
}
const { data } = params
validateUpdate(data)
const result = await updateConfig(params)
validatePatch(data)
const result = await patchConfig(params)
return res.send(result)
} catch (err) {
await logger.error('webComponentsConfig.patch', {
Expand All @@ -47,6 +48,28 @@ export const webComponentsConfigPatchHandler = async (req: AppRequest, res: AppR
}
}

export const webComponentsConfigPutHandler = async (req: AppRequest, res: AppResponse) => {
try {
const params = {
data: { ...req.body, customerId: req.params.customerId, appId: req.params.appId },
traceId: req.traceId,
}
const { data } = params
validateCreate(data)
const result = await putConfig(params)

return res.send(result)
} catch (err) {
await logger.error('webComponentsConfig.patch', {
traceId: req.traceId,
error: stringifyError(err),
headers: JSON.stringify(req.headers),
})

return res.send({ message: err.message, code: err.code, traceId: req.traceId })
}
}

export const webComponentsConfigDeleteHandler = async (req: AppRequest, res: AppResponse) => {
try {
const params = {
Expand Down Expand Up @@ -83,6 +106,7 @@ export const webComponentsConfigPostHandler = async (req: AppRequest, res: AppRe
webComponentsConfig.post('/:customerId/:appId', webComponentsConfigPostHandler)
webComponentsConfig.get('/:customerId/:appId', webComponentsConfigGetByIdHandler)
webComponentsConfig.delete('/:customerId/:appId', webComponentsConfigDeleteHandler)
webComponentsConfig.put('/:customerId/:appId', webComponentsConfigPatchHandler)
webComponentsConfig.put('/:customerId/:appId', webComponentsConfigPutHandler)
webComponentsConfig.patch('/:customerId/:appId', webComponentsConfigPatchHandler)

export default webComponentsConfig
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { WebComponentConfig } from './schema'

export type GetByClientIdParams = { traceId: string; data: Pick<WebComponentConfig, 'customerId'> }
export type GetByClientIdParams = { traceId: string; data: Pick<WebComponentConfig, 'customerId' | 'appId'> }
export type CreateParams = { traceId: string; data: WebComponentConfig }

export type UpdateParams = {
traceId: string
data: Partial<WebComponentConfig> & { customerId: WebComponentConfig['customerId'] }
data: Partial<WebComponentConfig> & { customerId: Pick<WebComponentConfig, 'customerId' | 'appId'> }
}

export type DeleteParams = { traceId: string; data: Pick<WebComponentConfig, 'customerId'> }
export type DeleteParams = { traceId: string; data: Pick<WebComponentConfig, 'customerId' | 'appId'> }
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 7735943

Please sign in to comment.