Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,25 @@
"deploy": "cdk deploy --all"
},
"dependencies": {
"@aws-sdk/client-dynamodb": "3.893.0",
"@aws-sdk/lib-dynamodb": "3.893.0",
"@aws-sdk/client-dynamodb": "3.913.0",
"@aws-sdk/lib-dynamodb": "3.913.0",
"constructs": "10.4.2",
"source-map-support": "0.5.21"
},
"devDependencies": {
"@troyblank/eslint-config-troyblank": "2.4.0",
"@types/chance": "1.1.7",
"@types/aws-lambda": "8.10.152",
"@types/aws-lambda": "8.10.156",
"@types/jest": "30.0.0",
"@types/node": "24.5.2",
"aws-cdk": "2.1029.2",
"aws-cdk-lib": "2.215.0",
"@types/node": "24.8.1",
"aws-cdk": "2.1030.0",
"aws-cdk-lib": "2.220.0",
"aws-lambda": "1.0.7",
"chance": "1.1.13",
"esbuild": "0.25.10",
"jest": "30.1.3",
"ts-jest": "29.4.4",
"typescript": "5.9.2"
"esbuild": "0.25.11",
"jest": "30.2.0",
"ts-jest": "29.4.5",
"typescript": "5.9.3"
},
"author": "Troy Blank",
"license": "BSD-3-Clause"
Expand Down
80 changes: 80 additions & 0 deletions src/lambdas/foodHow/getShoppingList.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Chance } from 'chance'
import { RESPONSE_CODE_OK, RESPONSE_CODE_SERVER_ERROR } from '../../constants/responseCodes'
import { mockShoppingListItems } from '../../mocks'
import { getShoppingList } from './utils/shoppingList'
import { handler } from './getShoppingList'

jest.mock('./utils/shoppingList')

describe('Lambda - Get Shopping List', () => {
const chance = new Chance()

beforeEach(() => {
process.env.shoppingListTableName = chance.word({ syllables: 4 })
})

it('should return a shopping list', async () => {
const shoppingList = mockShoppingListItems()
jest.mocked(getShoppingList).mockResolvedValue({
data: shoppingList,
errorMessage: undefined,
isError: false,
})

const expectedBody = {
shoppingList,
}
const result = await handler()

expect(result).toStrictEqual({
body: JSON.stringify(expectedBody),
headers: {
'Access-Control-Allow-Origin': '',
'Content-Type': 'application/json',
},
statusCode: RESPONSE_CODE_OK,
})
})

it('should return an error if there is problems getting a shopping list', async () => {
const errorMessage = chance.sentence()
jest.mocked(getShoppingList).mockResolvedValue({
data: undefined,
errorMessage: errorMessage,
isError: true,
})

const expectedBody = {
message: errorMessage,
}
const result = await handler()

expect(result).toStrictEqual({
body: JSON.stringify(expectedBody),
headers: {
'Access-Control-Allow-Origin': '',
'Content-Type': 'application/json',
},
statusCode: RESPONSE_CODE_SERVER_ERROR,
})
})

it('should return an error if there is problems using the getting a shopping list util', async () => {
const errorMessage = chance.sentence()
jest.mocked(getShoppingList).mockRejectedValue(errorMessage)

const expectedBody = {
message: errorMessage,
}
const result = await handler()

expect(result).toStrictEqual({
body: JSON.stringify(expectedBody),
headers: {
'Access-Control-Allow-Origin': '',
'Content-Type': 'application/json',
},
statusCode: RESPONSE_CODE_SERVER_ERROR,
})
})
})
30 changes: 30 additions & 0 deletions src/lambdas/foodHow/getShoppingList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { type APIGatewayProxyResult } from 'aws-lambda'
import { type DatabaseResponse } from '../../types'
import { RESPONSE_CODE_OK, RESPONSE_CODE_SERVER_ERROR } from '../../constants/responseCodes'
import { getShoppingList } from './utils/shoppingList'

export const handler = (): Promise<APIGatewayProxyResult> => new Promise((resolve) => {
const { accessControlAllowOrigin = '' } = process.env

const result: APIGatewayProxyResult = {
body: JSON.stringify({ message: 'Invalid state.', log: [] }),
headers: {
'Access-Control-Allow-Origin': accessControlAllowOrigin,
'Content-Type': 'application/json',
},
statusCode: RESPONSE_CODE_OK,
}

getShoppingList().then(({ data: shoppingList, isError, errorMessage }: DatabaseResponse) => {
if (isError) {
result.statusCode = RESPONSE_CODE_SERVER_ERROR
}

result.body = JSON.stringify({ message: errorMessage, shoppingList })
}).catch((error) => {
result.statusCode = RESPONSE_CODE_SERVER_ERROR
result.body = JSON.stringify({ message: error.toString() })
}).finally(() => {
resolve(result)
})
})
29 changes: 28 additions & 1 deletion src/lambdas/foodHow/utils/shoppingList.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand } from '@aws-sdk/lib-dynamodb'
import {
DynamoDBDocumentClient,
PutCommand,
ScanCommand,
type ScanCommandOutput,
} from "@aws-sdk/lib-dynamodb"
import { getErrorMessage } from '../../../utils/error'
import { type DatabaseResponse } from '../../../types'
import { type ShoppingListItem } from '../../../types/lambdas/foodHow'

export const getShoppingList = async (): Promise<DatabaseResponse> => {
const dynamoDbClient = new DynamoDBClient()
const dynamoDocumentClient = DynamoDBDocumentClient.from(dynamoDbClient)
const { shoppingListTableName } = process.env

try {
const data: ScanCommandOutput = await dynamoDocumentClient.send(new ScanCommand({
TableName: shoppingListTableName,
}))

return {
isError: false,
data: data.Items,
}
} catch (error: unknown) {
return {
isError: true,
errorMessage: getErrorMessage(error),
}
}
}

export const saveShoppingListItem = async (item: ShoppingListItem, userName: string): Promise<DatabaseResponse> => {
const dynamoDbClient = new DynamoDBClient()
const dynamoDocumentClient = DynamoDBDocumentClient.from(dynamoDbClient)
Expand Down
11 changes: 10 additions & 1 deletion src/lambdas/foodHow/utils/shoppingListError.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Chance } from 'chance'
import { mockShoppingListItem } from '../../../mocks'
import { saveShoppingListItem } from './shoppingList'
import { getShoppingList, saveShoppingListItem } from './shoppingList'

jest.mock('@aws-sdk/client-dynamodb', () => {
return {
Expand Down Expand Up @@ -29,6 +29,15 @@ describe('Shopping List Util - failure', () => {
process.env.shoppingListTableName = chance.word({ syllables: 4 })
})

it('Should allow fail when getting the shopping list.', async () => {
const result = await getShoppingList()

expect(result).toStrictEqual({
errorMessage: 'Something bad happened.',
isError: true,
})
})

it('Should allow fail when saving a shopping list item.', async () => {
const result = await saveShoppingListItem(mockShoppingListItem(), chance.name())

Expand Down
11 changes: 10 additions & 1 deletion src/lambdas/foodHow/utils/shoppingListSuccess.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Chance } from 'chance'
import { mockShoppingListItem } from '../../../mocks'
import { saveShoppingListItem } from './shoppingList'
import { getShoppingList, saveShoppingListItem } from './shoppingList'

jest.mock('@aws-sdk/client-dynamodb', () => ({
...jest.requireActual('@aws-sdk/client-dynamodb'),
Expand All @@ -25,6 +25,15 @@ describe('Shopping List Util - success', () => {
process.env.shoppingListTableName = chance.word({ syllables: 4 })
})

it('Should get the shopping list.', async () => {
const result = await getShoppingList()

expect(result).toStrictEqual({
data: [],
isError: false,
})
})

it('Should save a shopping list item.', async () => {
expect(async () => await saveShoppingListItem(mockShoppingListItem(), chance.name())).not.toThrow()
})
Expand Down
19 changes: 19 additions & 0 deletions src/stacks/foodHow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ export class FoodHowStack extends Stack {
},
})

const getShoppingList: NodejsFunction = new NodejsFunction(this, 'getShoppingList', {
functionName: `foodHowGetShoppingList${resourcePostFix}`,
entry: join(__dirname, '../lambdas', 'foodHow', 'getShoppingList.ts'),
handler: 'handler',
runtime: NODE_VERSION,
environment: {
accessControlAllowOrigin,
shoppingListTableName: shoppingListDb.tableName,
},
})

// ----------------------------------------------------------------------------------------
// AUTHORIZATION
// ----------------------------------------------------------------------------------------
Expand All @@ -75,6 +86,14 @@ export class FoodHowStack extends Stack {
basePath: 'foodhow',
})

// get shopping list items
const getShoppingListItemsLambdaIntegration: LambdaIntegration = new LambdaIntegration(getShoppingList)
const getShoppingListItemsLambdaResource: Resource = api.root.addResource('getShoppingList')

getShoppingListItemsLambdaResource.addMethod('GET', getShoppingListItemsLambdaIntegration, requiresAuthorization(authorizer))
shoppingListDb.grantReadWriteData(getShoppingList)
addCorsOptions(getShoppingListItemsLambdaResource, accessControlAllowOrigin)

// create shopping list item
const createShoppingListItemLambdaIntegration: LambdaIntegration = new LambdaIntegration(createShoppingListItem)
const createShoppingListItemLambdaResource: Resource = api.root.addResource('createShoppingListItem')
Expand Down
Loading