aws-lambda#APIGatewayProxyStructuredResultV2 TypeScript Examples
The following examples show how to use
aws-lambda#APIGatewayProxyStructuredResultV2.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: api-gateway.ts From MDDL with MIT License | 6 votes |
createJsonResponse = <T = any>(
body: T,
httpStatusCode = 200,
): APIGatewayProxyStructuredResultV2 => {
return {
cookies: [],
isBase64Encoded: false,
statusCode: httpStatusCode,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}
}
Example #2
Source File: api-gateway.ts From MDDL with MIT License | 6 votes |
createStatusCodeResponse = (
httpStatusCode = 200,
): APIGatewayProxyStructuredResultV2 => {
return {
cookies: [],
isBase64Encoded: false,
statusCode: httpStatusCode,
}
}
Example #3
Source File: api-gateway-v2-send-response.ts From oauth-app.js with MIT License | 6 votes |
export function sendResponse(
octokitResponse: OctokitResponse
): APIGatewayProxyStructuredResultV2 {
return {
statusCode: octokitResponse.status,
headers: octokitResponse.headers,
body: octokitResponse.text,
};
}
Example #4
Source File: api-gateway-v2.ts From oauth-app.js with MIT License | 6 votes |
export function createAWSLambdaAPIGatewayV2Handler(
app: OAuthApp<Options<ClientType>>,
{
pathPrefix,
onUnhandledRequest = onUnhandledRequestDefaultAWSAPIGatewayV2,
}: HandlerOptions & {
onUnhandledRequest?: (
event: APIGatewayProxyEventV2
) => Promise<APIGatewayProxyStructuredResultV2>;
} = {}
) {
return async function (event: APIGatewayProxyEventV2) {
const request = parseRequest(event);
const response = await handleRequest(app, { pathPrefix }, request);
return response ? sendResponse(response) : onUnhandledRequest(event);
};
}
Example #5
Source File: deleteDocumentById.test.ts From MDDL with MIT License | 5 votes |
describe('deleteDocumentById', () => {
const documentId = 'myDocumentId'
const fileId = 'myFileId'
const userId = 'myUserId'
let event: APIGatewayProxyEventV2
beforeEach(() => {
mockUserData(userId)
toMockedFunction(deleteDocument).mockImplementationOnce(async () => 1)
toMockedFunction(getDocumentById).mockImplementationOnce(async () =>
Document.fromDatabaseJson({
id: documentId,
ownerId: userId,
name: documentId,
files: [
File.fromDatabaseJson({
id: fileId,
name: fileId,
}),
],
}),
)
event = setUserId(
userId,
createMockEvent({
pathParameters: {
documentId,
},
}),
)
})
it('returns error if document could not be deleted', async () => {
toMockedFunction(deleteDocument)
.mockReset()
.mockImplementationOnce(async () => 0)
expect(await deleteDocumentById(event)).toMatchInlineSnapshot(`
Object {
"body": "{\\"message\\":\\"document could not be deleted\\"}",
"cookies": Array [],
"headers": Object {
"Content-Type": "application/json",
},
"isBase64Encoded": false,
"statusCode": 500,
}
`)
expect(toMockedFunction(deleteDocument)).toHaveBeenCalledWith(documentId)
})
it('returns success if document could be deleted', async () => {
const result = (await deleteDocumentById(
event,
)) as APIGatewayProxyStructuredResultV2
expect(result).toMatchInlineSnapshot(`
Object {
"cookies": Array [],
"isBase64Encoded": false,
"statusCode": 204,
}
`)
expect(toMockedFunction(deleteDocument)).toHaveBeenCalledWith(documentId)
})
})
Example #6
Source File: api-gateway-v2.ts From oauth-app.js with MIT License | 5 votes |
async function onUnhandledRequestDefaultAWSAPIGatewayV2(
event: APIGatewayProxyEventV2
): Promise<APIGatewayProxyStructuredResultV2> {
const request = parseRequest(event);
const response = onUnhandledRequestDefault(request);
return sendResponse(response);
}
Example #7
Source File: createCollectionForUser.test.ts From MDDL with MIT License | 4 votes |
describe('createCollectionForUser', () => {
const userId = 'myUserId'
let event: APIGatewayProxyEventV2
beforeEach(() => {
mockUserData(userId)
toMockedFunction(getDocumentsByIdsAndOwnerId).mockImplementationOnce(
async (docIds) =>
docIds.map((id) =>
Document.fromDatabaseJson({
id,
name: '' + id,
}),
),
)
toMockedFunction(emailIsWhitelisted).mockImplementationOnce(() => true)
event = setUserId(
userId,
createMockEvent({
pathParameters: {
userId,
},
}),
)
})
it('fails validation on no body', async () => {
expect(await createCollectionForUser(event)).toEqual(
expect.objectContaining({
body: '{"message":"validation error: body was expected but empty"}',
}),
)
})
it('validation is applied', async () => {
event.body = JSON.stringify({})
expect(await createCollectionForUser(event)).toEqual(
expect.objectContaining({
body:
'{"message":"validation error: \\"name\\" is required, \\"documentIds\\" is required, \\"individualEmailAddresses\\" is required"}',
}),
)
})
it('fails validation with unwhitelisted email address', async () => {
toMockedFunction(emailIsWhitelisted)
.mockReset()
.mockImplementationOnce(() => false)
event.body = JSON.stringify({
name: 'test',
documentIds: ['abc1234'],
individualEmailAddresses: ['[email protected]'],
})
expect(await createCollectionForUser(event)).toMatchInlineSnapshot(`
Object {
"body": "{\\"message\\":\\"validation error: \\\\\\"individualEmailAddresses[0]\\\\\\" failed custom validation because [email protected] is not a whitelisted email address\\"}",
"cookies": Array [],
"headers": Object {
"Content-Type": "application/json",
},
"isBase64Encoded": false,
"statusCode": 400,
}
`)
})
it('validation requires documentIds to be populated', async () => {
event.body = JSON.stringify({
name: 'test',
documentIds: [],
individualEmailAddresses: [],
})
expect(await createCollectionForUser(event)).toEqual(
expect.objectContaining({
body:
'{"message":"validation error: \\"documentIds\\" must contain at least 1 items"}',
}),
)
})
it('fails if documents do not belong to user', async () => {
event.body = JSON.stringify({
name: 'test',
documentIds: ['abc1234'],
individualEmailAddresses: ['[email protected]'],
})
toMockedFunction(getDocumentsByIdsAndOwnerId)
.mockReset()
.mockImplementationOnce(async () => [])
expect(await createCollectionForUser(event)).toEqual(
expect.objectContaining({
body: '{"message":"validation error: documents not found"}',
}),
)
})
it('creates collection', async () => {
const ownerId = 'myOwnerId'
const documentId = 'myDocumentId'
toMockedFunction(createCollection).mockImplementationOnce(() =>
Promise.resolve(
CollectionModel.fromJson({
id: documentId,
ownerId: ownerId,
name: 'My First File',
createdAt: new Date('2015-01-12T13:14:15Z'),
createdBy: ownerId,
updatedBy: ownerId,
}),
),
)
event.body = JSON.stringify({
name: 'test',
documentIds: ['abc1234'],
individualEmailAddresses: ['[email protected]'],
})
const result = (await createCollectionForUser(
event,
)) as APIGatewayProxyStructuredResultV2
expect(result.statusCode).toEqual(200)
const response = JSON.parse(result.body as string)
expect(response).toEqual(
expect.objectContaining({
createdDate: '2015-01-12T13:14:15.000Z',
name: 'My First File',
id: documentId,
links: expect.arrayContaining([
expect.objectContaining({ rel: 'grants' }),
expect.objectContaining({ rel: 'documents' }),
]),
}),
)
expect(getObjectKeys(response)).toMatchInlineSnapshot(`
Array [
"name",
"createdDate",
"id",
"links[0].href",
"links[0].rel",
"links[0].type",
"links[1].href",
"links[1].rel",
"links[1].type",
]
`)
})
})
Example #8
Source File: createDocumentForUser.test.ts From MDDL with MIT License | 4 votes |
describe('createDocumentForUser', () => {
const userId = 'myUserId'
let event: APIGatewayProxyEventV2
beforeEach(() => {
mockUserData(userId)
event = setUserId(
userId,
createMockEvent({
pathParameters: {
userId,
},
}),
)
})
it('fails validation on no body', async () => {
expect(await createDocumentForUser(event)).toEqual(
expect.objectContaining({
body: '{"message":"validation error: body was expected but empty"}',
}),
)
})
it('validation is applied', async () => {
event.body = JSON.stringify({})
expect(await createDocumentForUser(event)).toEqual(
expect.objectContaining({
body:
'{"message":"validation error: \\"name\\" is required, \\"files\\" is required"}',
}),
)
})
it('validation requires files to be populated', async () => {
event.body = JSON.stringify({ name: 'test', files: [] })
expect(await createDocumentForUser(event)).toEqual(
expect.objectContaining({
body:
'{"message":"validation error: \\"files\\" must contain at least 1 items"}',
}),
)
})
it('validation requires file to populated correctly', async () => {
event.body = JSON.stringify({ name: 'test', files: [{}] })
expect(await createDocumentForUser(event)).toEqual(
expect.objectContaining({
body:
'{"message":"validation error: \\"files[0].name\\" is required, \\"files[0].contentLength\\" is required, \\"files[0].contentType\\" is required, \\"files[0].sha256Checksum\\" is required"}',
}),
)
})
it('checks max count of documents', async () => {
toMockedFunction(countDocumentsByOwnerId).mockImplementationOnce(
async () => 100,
)
event.body = JSON.stringify({
name: 'test',
files: [
{
name: 'MyFile1.jpg',
contentLength: 1000,
contentType: 'image/jpeg',
sha256Checksum: 'ABC123',
},
],
})
const result = (await createDocumentForUser(
event,
)) as APIGatewayProxyStructuredResultV2
expect(result).toMatchInlineSnapshot(`
Object {
"body": "{\\"message\\":\\"validation error: maximum document count of 100 reached\\"}",
"cookies": Array [],
"headers": Object {
"Content-Type": "application/json",
},
"isBase64Encoded": false,
"statusCode": 400,
}
`)
})
it('validation passes', async () => {
const documentId = 'myDocumentId'
const fileId = 'myFileId'
toMockedFunction(createDocument).mockImplementationOnce(() =>
Promise.resolve(
DocumentModel.fromJson({
id: documentId,
ownerId: userId,
name: 'My First File',
createdAt: new Date('2015-01-12T13:14:15Z'),
createdBy: userId,
updatedBy: userId,
files: [
{
id: fileId,
documentId,
name: 'MyFile1.jpg',
path: createFilePath(userId, documentId, fileId),
received: false,
sha256Checksum: 'ABC123',
contentType: 'image/jpeg',
createdAt: new Date('2015-01-12T13:14:15Z'),
createdBy: userId,
contentLength: 1000,
},
],
}),
),
)
event.body = JSON.stringify({
name: 'test',
files: [
{
name: 'MyFile1.jpg',
contentLength: 1000,
contentType: 'image/jpeg',
sha256Checksum: 'ABC123',
},
],
})
const result = (await createDocumentForUser(
event,
)) as APIGatewayProxyStructuredResultV2
expect(result.statusCode).toEqual(200)
const response = JSON.parse(result.body as string)
expect(response).toEqual(
expect.objectContaining({
createdDate: '2015-01-12T13:14:15.000Z',
name: 'My First File',
id: 'myDocumentId',
files: [
{
createdDate: '2015-01-12T13:14:15.000Z',
id: 'myFileId',
links: [
{
href:
'https://presigned-url.for/documents/myUserId/myDocumentId/myFileId+ABC123',
includeFormData: {
'Content-Length': 1000,
'Content-Type': 'image/jpeg',
},
rel: 'upload',
type: 'POST',
},
],
name: 'MyFile1.jpg',
sha256Checksum: 'ABC123',
contentLength: 1000,
contentType: 'image/jpeg',
},
],
}),
)
expect(getObjectKeys(response)).toMatchInlineSnapshot(`
Array [
"createdDate",
"name",
"id",
"files[0].id",
"files[0].createdDate",
"files[0].links[0].href",
"files[0].links[0].rel",
"files[0].links[0].type",
"files[0].links[0].includeFormData.Content-Type",
"files[0].links[0].includeFormData.Content-Length",
"files[0].name",
"files[0].sha256Checksum",
"files[0].contentType",
"files[0].contentLength",
"links[0].href",
"links[0].rel",
"links[0].type",
"links[1].href",
"links[1].rel",
"links[1].type",
"links[2].href",
"links[2].rel",
"links[2].type",
]
`)
})
})
Example #9
Source File: putDocumentById.test.ts From MDDL with MIT License | 4 votes |
describe('putDocumentById', () => {
const documentId = 'myDocumentId'
const userId = 'myUserId'
let event: APIGatewayProxyEventV2
beforeEach(() => {
mockUserData(userId)
toMockedFunction(getDocumentById).mockImplementationOnce(async () =>
Document.fromDatabaseJson({
id: documentId,
ownerId: userId,
name: documentId,
}),
)
event = setUserId(
userId,
createMockEvent({
pathParameters: {
documentId,
},
}),
)
})
it('fails validation on no body', async () => {
expect(await putDocumentById(event)).toEqual(
expect.objectContaining({
body: '{"message":"validation error: body was expected but empty"}',
}),
)
})
it('validation requires name or description', async () => {
event.body = JSON.stringify({})
expect(await putDocumentById(event)).toEqual(
expect.objectContaining({
body:
'{"message":"validation error: \\"value\\" must contain at least one of [name, description]"}',
}),
)
})
it('updates name', async () => {
toMockedFunction(updateDocument).mockImplementationOnce(async () => 1)
const body = {
name: 'test update',
}
event.body = JSON.stringify(body)
const result = (await putDocumentById(
event,
)) as APIGatewayProxyStructuredResultV2
expect(result).toMatchInlineSnapshot(`
Object {
"cookies": Array [],
"isBase64Encoded": false,
"statusCode": 204,
}
`)
expect(toMockedFunction(updateDocument)).toHaveBeenCalledWith(
documentId,
expect.objectContaining(body),
)
})
it('updates description', async () => {
toMockedFunction(updateDocument).mockImplementationOnce(async () => 1)
const body = {
description: 'test update',
}
event.body = JSON.stringify(body)
const result = (await putDocumentById(
event,
)) as APIGatewayProxyStructuredResultV2
expect(result).toMatchInlineSnapshot(`
Object {
"cookies": Array [],
"isBase64Encoded": false,
"statusCode": 204,
}
`)
expect(toMockedFunction(updateDocument)).toHaveBeenCalledWith(
documentId,
expect.objectContaining(body),
)
})
})