Skip to content

Instantly share code, notes, and snippets.

@scionwest
Created December 13, 2020 03:37
Show Gist options
  • Save scionwest/2725d939b7cc3b69d8bfa9fea2b5230c to your computer and use it in GitHub Desktop.
Save scionwest/2725d939b7cc3b69d8bfa9fea2b5230c to your computer and use it in GitHub Desktop.
import 'mocha';
import { expect } from 'chai';
import * as sinon from 'sinon';
import { DynamoDB } from 'aws-sdk';
import { handler } from '../../src/handlers/post-item';
import { ApiGatewayResponse } from '../../src/models/apigateway/apigateway-response';
import { ApiGatewayEventMock } from '../models/apigateway-event-mock';
describe('Lambda handler', () => {
describe('Lambda handler validation', () => {
it('should return a 422 status code when body is missing "id" field', async () => {
const event = new ApiGatewayEventMock();
event.body = '{ "title": "test", "isCompleted": "false"}';
const lambdaResponse: ApiGatewayResponse = await handler(event);
expect(lambdaResponse).to.have.property('statusCode');
expect(lambdaResponse.statusCode).to.equal(422);
});
it('should return a 422 status code when body is missing "title" field', async () => {
const event = new ApiGatewayEventMock();
event.body = '{ "id": "1", "isCompleted": "false"}';
const lambdaResponse: ApiGatewayResponse = await handler(event);
expect(lambdaResponse).to.have.property('statusCode');
expect(lambdaResponse.statusCode).to.equal(422);
});
it('should return a 422 status code when body is missing "isComplete" field', async () => {
const event = new ApiGatewayEventMock();
event.body = '{ "id": "1", "isCompleted": "false"}';
const lambdaResponse: ApiGatewayResponse = await handler(event);
expect(lambdaResponse).to.have.property('statusCode');
expect(lambdaResponse.statusCode).to.equal(422);
});
});
});
import { DynamoDB } from 'aws-sdk';
import { ApiGatewayEvent } from '../models/apigateway/apigateway-event';
import { ApiGatewayResponse } from '../models/apigateway/apigateway-response';
import { TodoItem } from '../models/todo-item';
export const handler = async (event: ApiGatewayEvent): Promise<ApiGatewayResponse> => {
try {
const todo: TodoItem = JSON.parse(event.body);
if (!todo.title) {
return { statusCode: 422 };
} else if (!todo.isComplete) {
todo.isComplete = false;
} else if (!todo.id) {
return { statusCode: 422 };
}
const docClient = new DynamoDB.DocumentClient();
const tableName = process.env['SAMPLE_TABLE'];
if (!tableName) {
console.log('SAMPLE_TABLE environment variable is missing');
return { statusCode: 500 };
}
const params: DynamoDB.DocumentClient.PutItemInput = {
TableName: tableName,
Item: todo
};
await docClient.put(params).promise();
return { statusCode: 201, body: todo };
} catch(err) {
console.log(err);
return { statusCode: 500 };
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment