Skip to content

Commit

Permalink
fix: refactor proxy and add deprecation warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
brett-vendia committed Feb 18, 2021
1 parent 4b5ca7a commit d50b7e7
Show file tree
Hide file tree
Showing 6 changed files with 172 additions and 140 deletions.
62 changes: 59 additions & 3 deletions __tests__/integration.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ describe.each(EACH_MATRIX)('%s:%s: integration tests', (eventSourceName, framewo
serverlessExpressInstance = serverlessExpress({ app })
})

test('handler returns promise', () => {
test('serverlessExpressInstance returns promise', () => {
const event = makeEvent({
eventSourceName,
path: '/',
httpMethod: 'GET'
})
const response = serverlessExpressInstance.handler(event)
const response = serverlessExpressInstance(event)
expect(response.then).toBeTruthy()
})

Expand Down Expand Up @@ -452,7 +452,7 @@ describe.each(EACH_MATRIX)('%s:%s: integration tests', (eventSourceName, framewo
// expect(customLogger.debug.mock.calls.length).toBe(0)
})

test('legacy/deprecated usage', async () => {
test('legacy/deprecated createServer', async () => {
const serverlessExpressMiddleware = require('../src/middleware')
app = express()
router = express.Router()
Expand Down Expand Up @@ -484,4 +484,60 @@ describe.each(EACH_MATRIX)('%s:%s: integration tests', (eventSourceName, framewo
})
expect(response).toEqual(expectedResponse)
})

test('legacy/deprecated handler', async () => {
const serverlessExpressMiddleware = require('../src/middleware')
router.use(serverlessExpressMiddleware.eventContext())
router.get('/users', (req, res) => {
const { event } = req.apiGateway
const eventPath = event.path || event.rawPath || event.Records[0].cf.request.uri
res.json({
path: eventPath
})
})
const event = makeEvent({
eventSourceName,
path: '/users',
httpMethod: 'GET'
})
const response = await serverlessExpressInstance.handler(event)
const expectedResponse = makeResponse({
eventSourceName,
body: JSON.stringify({ path: '/users' }),
multiValueHeaders: {
'content-length': ['17'],
etag: ['W/"11-eM8YArY+qNwdvTL2ppeAaFc4Oq8"']
},
statusCode: 200
})
expect(response).toEqual(expectedResponse)
})

test('legacy/deprecated proxy', async () => {
const serverlessExpressMiddleware = require('../src/middleware')
router.use(serverlessExpressMiddleware.eventContext())
router.get('/users', (req, res) => {
const { event } = req.apiGateway
const eventPath = event.path || event.rawPath || event.Records[0].cf.request.uri
res.json({
path: eventPath
})
})
const event = makeEvent({
eventSourceName,
path: '/users',
httpMethod: 'GET'
})
const response = await serverlessExpressInstance.proxy({ event })
const expectedResponse = makeResponse({
eventSourceName,
body: JSON.stringify({ path: '/users' }),
multiValueHeaders: {
'content-length': ['17'],
etag: ['W/"11-eM8YArY+qNwdvTL2ppeAaFc4Oq8"']
},
statusCode: 200
})
expect(response).toEqual(expectedResponse)
})
})
13 changes: 12 additions & 1 deletion src/configure.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import { RequestListener } from "http"
import { Handler } from "aws-lambda"
import Logger from "./logger"
import ProxyParams from "./proxy"

interface ProxyParams {
app: RequestListener,
binaryMimeTypes?: string[],
binarySettings?: BinarySettings
}

interface BinarySettings {
isBinary?: Function | boolean,
contentTypes?: string[]
}
interface ConfigureParams {
app: RequestListener,
binaryMimeTypes?: string[],
Expand All @@ -22,4 +31,6 @@ interface ConfigureResult {

declare function configure(configureParams: ConfigureParams): ConfigureResult

// declare function proxy(proxyParams: ProxyParams): Promise<any>

export default configure
136 changes: 100 additions & 36 deletions src/configure.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
const { getFramework } = require('./frameworks')
const util = require('util')
const logger = require('./logger')
const proxy = require('./proxy')
const { setCurrentInvoke } = require('./current-invoke')
const { getEventSource } = require('./event-sources')
const { getEventSourceNameBasedOnEvent } = require('./event-sources/utils')
const { getFramework } = require('./frameworks')
const makeResolver = require('./make-resolver')
const { forwardRequestToNodeServer, respondToEventSourceWithError } = require('./transport')

const DEFAULT_BINARY_ENCODINGS = ['gzip', 'deflate', 'br']
const DEFAULT_BINARY_CONTENT_TYPES = ['image/*']

function getDefaultBinarySettings (deprecatedBinaryMimeTypes) {
return {
contentTypes: deprecatedBinaryMimeTypes || DEFAULT_BINARY_CONTENT_TYPES,
contentEncodings: DEFAULT_BINARY_ENCODINGS
}
}

function configure ({
app: configureApp,
Expand All @@ -12,44 +27,93 @@ function configure ({
resolutionMode: configureResolutionMode = 'PROMISE',
eventSourceName: configureEventSourceName,
eventSource: configureEventFns,
respondWithErrors: configureRespondWithErrors = process.env.NODE_ENV === 'development',
proxy: configureProxy = ({
app: configureProxyApp = configureApp,
framework: configureProxyFramework = configureFramework,
respondWithErrors: configureRespondWithErrors = process.env.NODE_ENV === 'development'
} = {}) {
function proxy ({
app = configureApp,
framework = configureFramework,
event = {},
context = {},
callback = null,
resolutionMode = configureResolutionMode,
event,
context,
callback,
eventSourceName = configureEventSourceName,
eventSourceName = configureEventSourceName || getEventSourceNameBasedOnEvent({ event }),
binaryMimeTypes = configureBinaryMimeTypes,
binarySettings = configureBinarySettings,
eventSource = configureEventFns,
binarySettings = configureBinarySettings || getDefaultBinarySettings(binaryMimeTypes),
eventSource = configureEventFns || getEventSource({ eventSourceName }),
log = configureLog,
respondWithErrors = configureRespondWithErrors
} = {}) => proxy({
app: configureProxyApp,
framework: configureProxyFramework,
event,
context,
resolutionMode,
callback,
eventSourceName,
binaryMimeTypes,
binarySettings,
eventSource,
log,
respondWithErrors
}),
handler: configureHandler = (event, context, callback) => configureProxy({
event,
context,
callback
})
} = {}) {
configureHandler.handler = configureHandler
configureHandler.proxy = configureProxy
configureHandler.log = configureLog
return configureHandler
}) {
log.debug('SERVERLESS_EXPRESS:PROXY', {
event: util.inspect(event, { depth: null }),
context: util.inspect(context, { depth: null }),
resolutionMode,
eventSourceName,
binarySettings,
respondWithErrors
})

if (binaryMimeTypes) {
console.warn('[DEPRECATION NOTICE] { binaryMimeTypes: [] } is deprecated. base64 encoding is now automatically determined based on response content-type and content-encoding. If you need to manually set binary content types, instead, use { binarySettings: { contentTypes: [] } }')
}

setCurrentInvoke({ event, context })
return new Promise((resolve, reject) => {
const promise = {
resolve,
reject
}
const resolver = makeResolver({
context,
callback,
promise,
resolutionMode
})

try {
forwardRequestToNodeServer({
app,
framework,
event,
context,
resolver,
eventSourceName,
binarySettings,
eventSource,
log
})
} catch (error) {
respondToEventSourceWithError({
error,
resolver,
log,
respondWithErrors,
eventSource
})
}
})
}

function handler (event, context, callback) {
return proxy({
event,
context,
callback
})
}

handler.handler = (...params) => {
console.warn('[DEPRECATION NOTICE] You\'re using the deprecated `serverlessExpress({...}).handler({...})` method. This will be removed in a future version of @vendia/serverless-express. Instead, simply return `serverlessExpress({...})` as your handler.')
return handler(...params)
}

handler.proxy = (...params) => {
console.warn('[DEPRECATION NOTICE] You\'re using the deprecated `serverlessExpress({...}).proxy({...})` method. This will be removed in a future version of @vendia/serverless-express. Instead, simply return `serverlessExpress({...})` as your handler.')
return proxy(...params)
}

handler.log = configureLog

return handler
}

module.exports = configure
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports.configure = configure
// Legacy/deprecated:

function createServer (app, serverListenCallback, binaryMimeTypes) {
console.warn('You\'re using the deprecated createServer method that will be removed in the next major version. See https://github.com/vendia/serverless-express/blob/mainline/UPGRADE.md to upgrade.')
console.warn('[DEPRECATION NOTICE] You\'re using the deprecated createServer method that will be removed in the next major version. See https://github.com/vendia/serverless-express/blob/mainline/UPGRADE.md to upgrade.')

if (serverListenCallback) {
throw new Error('serverListenCallback is no longer supported.')
Expand Down
16 changes: 0 additions & 16 deletions src/proxy.d.ts

This file was deleted.

83 changes: 0 additions & 83 deletions src/proxy.js

This file was deleted.

0 comments on commit d50b7e7

Please sign in to comment.