Skip to content

Commit f079b11

Browse files
Add basic pagination and json:api response
1 parent e126397 commit f079b11

File tree

2 files changed

+60
-4
lines changed

2 files changed

+60
-4
lines changed

lambdas/api-handler/src/handlers/__tests__/get-letters.test.ts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,30 @@ import type { Context } from 'aws-lambda';
33
import { mockDeep } from 'jest-mock-extended';
44

55
describe('API Lambda handler', () => {
6-
it('returns 200 OK with "Here are some letters: [L1, L2, L3]" for the root path', async () => {
6+
it('returns 200 OK with basic paginated resources', async () => {
77
const event = { path: '/letters' };
88
const context = mockDeep<Context>();
99
const callback = jest.fn();
1010
const result = await getLetters(event, context, callback);
1111

12+
const expected = {
13+
"links": {
14+
"self": "/letters?page=1",
15+
"first": "/letters?page=1",
16+
"last": "/letters?page=1",
17+
"next": "/letters?page=1",
18+
"prev": "/letters?page=1"
19+
},
20+
"data": [
21+
{ "type": "letter", "id": "l1" },
22+
{ "type": "letter", "id": "l2" },
23+
{ "type": "letter", "id": "l3" }
24+
]
25+
}
26+
1227
expect(result).toEqual({
1328
statusCode: 200,
14-
body: 'Here are some letters: [L1, L2, L3]',
29+
body: JSON.stringify(expected),
1530
});
1631
});
1732

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1-
// Replace me with the actual code for your Lambda function
21
import { Handler, APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
32

3+
const storedLetters: string[] = ["l1", "l2", "l3"];
4+
45
export const getLetters: Handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
56

67
if (event.path === '/letters') {
8+
9+
const response = createGetLettersResponse(event.path, storedLetters);
10+
711
return {
812
statusCode: 200,
9-
body: 'Here are some letters: [L1, L2, L3]',
13+
body: JSON.stringify(response)
1014
};
1115
}
1216

@@ -15,3 +19,40 @@ export const getLetters: Handler = async (event: APIGatewayProxyEvent): Promise<
1519
body: 'Not Found',
1620
};
1721
};
22+
23+
interface Link {
24+
self: string;
25+
first: string;
26+
last: string;
27+
next?: string;
28+
prev?: string;
29+
}
30+
31+
interface Resource {
32+
type: string;
33+
id: string;
34+
}
35+
36+
interface GetLettersResponse {
37+
links: Link;
38+
data: Resource[];
39+
}
40+
41+
function createGetLettersResponse(
42+
baseUrl: string,
43+
letters: string[]
44+
): GetLettersResponse {
45+
return {
46+
links: {
47+
self: `${baseUrl}?page=1`,
48+
first: `${baseUrl}?page=1`,
49+
last: `${baseUrl}?page=1`,
50+
next: `${baseUrl}?page=1`,
51+
prev: `${baseUrl}?page=1`
52+
},
53+
data: letters.map((letterId) => ({
54+
type: "letter",
55+
id: letterId,
56+
})),
57+
};
58+
}

0 commit comments

Comments
 (0)