Skip to content

Commit 671f506

Browse files
authored
Merge pull request #48 from onicagroup/issue36
Issue #36 Upgrade to Middy v1.0
2 parents 3011e28 + 7275e2b commit 671f506

File tree

6 files changed

+7003
-2397
lines changed

6 files changed

+7003
-2397
lines changed

docs/source/lambda_utils.rst

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,11 @@ Used with API Gateway, the included middlewares:
3434
instance will not be destroyed and suffer a cold start on the next invocation.
3535
- Leverages async syntax.
3636

37-
See `Middy middlewares <https://middy.js.org/docs/middlewares.html>`_ for details on those.
37+
See `Middy middlewares <https://middy.js.org/#available-middlewares>`_ for details on those.
3838
Not all Middy middlewares are in this implementation, only common ones that are generally useful in all
3939
APIs. You may extend LambdaUtils's ``wrapApiHandler()`` function in your projects,
4040
or use it as an example to write your own, to add more middleware!
4141

42-
**WARNING**: Middy has, historically, introduced some `breaking changes <https://github.com/onicagroup/sailplane/issues/16>`_
43-
in previous minor version bumps. LambdaUtils has been built and tested with Middy
44-
0.29.0, and should continue to work with future versions, but bumping your
45-
Middy version beyond 0.29.0 may produce some weird errors.
46-
47-
4842
``LambdaUtils`` depends on two other utilities to work:
4943

5044
- :doc:`logger`
@@ -53,9 +47,26 @@ Middy version beyond 0.29.0 may produce some weird errors.
5347
Install
5448
^^^^^^^
5549

50+
**To use LambdaUtils v3.x with Middy v1.x.x (latest):**
51+
52+
.. code-block:: shell
53+
54+
npm install @sailplane/lambda-utils@3 @sailplane/logger @middy/core @middy/http-cors @middy/http-event-normalizer @middy/http-header-normalizer @middy/http-json-body-parser
55+
56+
The extra @middy/ middleware packages are optional if you write your own wrapper function that does not use them. See below.
57+
58+
**To use LambdaUtils v2.x with Middy v0.x.x:**
59+
5660
.. code-block:: shell
5761
58-
npm install @sailplane/lambda-utils @sailplane/logger middy
62+
npm install @sailplane/lambda-utils@2 @sailplane/logger middy
63+
64+
Upgrading
65+
^^^^^^^^^
66+
67+
To upgrade from lambda-utils v1.x or v2.x to the latest, remove the old with ``npm rm middy``
68+
and then follow the install instructions above to install the latest. See also the
69+
`Middy upgrade instructions <https://middy.js.org/UPGRADE.html>`_.
5970

6071
Examples
6172
^^^^^^^^

lambda-utils/lib/lambda-utils.test.ts

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ describe("LambdaUtils", () => {
1212

1313
test("wrapApiHandler apiSuccess", (endTest) => {
1414
// GIVEN
15-
const expectResult = { hello: 'world' };
16-
17-
const handler = LambdaUtils.wrapApiHandler(async (event: APIGatewayEvent): Promise<APIGatewayProxyResult> => {
15+
const handler = LambdaUtils.wrapApiHandler(async (event: LambdaUtils.APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
1816
// Echo the event back
1917
return LambdaUtils.apiSuccess(event);
2018
});
@@ -52,10 +50,10 @@ describe("LambdaUtils", () => {
5250
expect(resultEvent.body).toEqual(body);
5351

5452
// Headers are normalized in request event
55-
expect(resultEvent.headers['content-length']).toBeUndefined();
56-
expect(resultEvent.headers['Content-Length']).toEqual('0');
53+
expect(resultEvent.headers['Content-Length']).toBeUndefined();
54+
expect(resultEvent.headers['content-length']).toEqual('0');
5755
expect(resultEvent.headers["CONTENT-TYPE"]).toBeUndefined();
58-
expect(resultEvent.headers['Content-Type']).toEqual("application/json");
56+
expect(resultEvent.headers['content-type']).toEqual("application/json");
5957

6058
// pathParameters and queryStringParameters are expanded to empty objects
6159
expect(resultEvent.pathParameters).toEqual({});
@@ -67,9 +65,7 @@ describe("LambdaUtils", () => {
6765

6866
test("wrapApiHandler promise object success", (endTest) => {
6967
// GIVEN
70-
const expectResult = { hello: 'world' };
71-
72-
const handler = LambdaUtils.wrapApiHandler(async (event: APIGatewayEvent): Promise<any> => {
68+
const handler = LambdaUtils.wrapApiHandler(async (): Promise<any> => {
7369
return {message: 'Hello'};
7470
});
7571

@@ -103,9 +99,7 @@ describe("LambdaUtils", () => {
10399

104100
test("wrapApiHandler promise empty success", (endTest) => {
105101
// GIVEN
106-
const expectResult = { hello: 'world' };
107-
108-
const handler = LambdaUtils.wrapApiHandler(async (event: APIGatewayEvent): Promise<any> => {
102+
const handler = LambdaUtils.wrapApiHandler(async (): Promise<any> => {
109103
return;
110104
});
111105

@@ -139,7 +133,7 @@ describe("LambdaUtils", () => {
139133

140134
test("wrapApiHandler throw Error", (endTest) => {
141135
// GIVEN
142-
const handler = LambdaUtils.wrapApiHandler(async (event: APIGatewayEvent): Promise<APIGatewayProxyResult> => {
136+
const handler = LambdaUtils.wrapApiHandler(async (): Promise<APIGatewayProxyResult> => {
143137
throw new Error("oops");
144138
});
145139

@@ -157,7 +151,7 @@ describe("LambdaUtils", () => {
157151

158152
test("wrapApiHandler throw http-error", (endTest) => {
159153
// GIVEN
160-
const handler = LambdaUtils.wrapApiHandler(async (event: APIGatewayEvent): Promise<APIGatewayProxyResult> => {
154+
const handler = LambdaUtils.wrapApiHandler(async (): Promise<APIGatewayProxyResult> => {
161155
throw new createError.NotFound();
162156
});
163157

lambda-utils/lib/lambda-utils.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@ import {
44
Context,
55
ProxyResult
66
} from "aws-lambda";
7-
import * as middy from "middy";
8-
import {cors, httpEventNormalizer, httpHeaderNormalizer, jsonBodyParser} from "middy/middlewares";
7+
8+
import middy from '@middy/core';
9+
import cors from '@middy/http-cors';
10+
import httpEventNormalizer from '@middy/http-event-normalizer';
11+
import httpHeaderNormalizer from '@middy/http-header-normalizer';
12+
import httpJsonBodyParser from '@middy/http-json-body-parser';
913
import {Logger} from "@sailplane/logger";
1014

1115
const logger = new Logger('lambda-utils');
@@ -40,7 +44,7 @@ export type AsyncProxyHandler = (event: APIGatewayProxyEvent, context: Context)
4044
* Fine tuned to work better than the Middy version.
4145
*/
4246
export const unhandledExceptionMiddleware = () => ({
43-
onError: (handler: middy.HandlerLambda<APIGatewayEvent,ProxyResult>, next: middy.NextFunction) => {
47+
onError: (handler: middy.HandlerLambda<APIGatewayEvent, ProxyResult>, next: middy.NextFunction) => {
4448

4549
logger.error('Unhandled exception:', handler.error);
4650

@@ -62,7 +66,7 @@ export const unhandledExceptionMiddleware = () => ({
6266
* Must be registered as the last (thus first to run) "after" middleware.
6367
*/
6468
export const resolvedPromiseIsSuccessMiddleware = () => ({
65-
after: (handler: middy.HandlerLambda<APIGatewayEvent,ProxyResult>, next: middy.NextFunction) => {
69+
after: (handler: middy.HandlerLambda<APIGatewayEvent, ProxyResult>, next: middy.NextFunction) => {
6670
// If response isn't a proper API result object, convert it into one.
6771
let r = handler.response;
6872
if (!r || typeof r !== 'object' || (!r.statusCode && !r.body)) {
@@ -96,9 +100,9 @@ export const resolvedPromiseIsSuccessMiddleware = () => ({
96100
* @see https://middy.js.org/docs/middlewares.html
97101
* @see https://www.npmjs.com/package/http-errors
98102
*/
99-
export function wrapApiHandler(handler: AsyncProxyHandler): middy.Middy<APIGatewayEvent,ProxyResult> {
103+
export function wrapApiHandler(handler: AsyncProxyHandler): middy.Middy<AWS_APIGatewayProxyEvent, ProxyResult> {
100104
return middy(handler)
101-
.use(httpEventNormalizer()).use(httpHeaderNormalizer()).use(jsonBodyParser())
105+
.use(httpEventNormalizer()).use(httpHeaderNormalizer()).use(httpJsonBodyParser())
102106
.use(cors())
103107
.use(resolvedPromiseIsSuccessMiddleware())
104108
.use(unhandledExceptionMiddleware());

0 commit comments

Comments
 (0)