Skip to content

Commit

Permalink
refactor: import from namespace (#1405)
Browse files Browse the repository at this point in the history
Co-authored-by: andrew <andrew@emergetools.com>
  • Loading branch information
dnalborczyk and andrew committed May 12, 2022
1 parent a353d31 commit ed9d6cd
Show file tree
Hide file tree
Showing 33 changed files with 182 additions and 127 deletions.
4 changes: 3 additions & 1 deletion examples/events/http/handler.js
@@ -1,8 +1,10 @@
'use strict'

const { stringify } = JSON

exports.hello = async function hello() {
return {
body: JSON.stringify({ foo: 'bar', IS_OFFLINE: process.env.IS_OFFLINE }),
body: stringify({ foo: 'bar', IS_OFFLINE: process.env.IS_OFFLINE }),
statusCode: 200,
}
}
6 changes: 4 additions & 2 deletions src/events/authValidateContext.js
@@ -1,6 +1,8 @@
import Boom from '@hapi/boom'
import serverlessLog from '../serverlessLog.js'

const { keys, values } = Object

function internalServerError(message) {
const errorType = 'AuthorizerConfigurationException'

Expand All @@ -13,14 +15,14 @@ function internalServerError(message) {
}

function isValidContext(context) {
return Object.values(context).every(
return values(context).every(
(i) =>
typeof i === 'string' || typeof i === 'boolean' || typeof i === 'number',
)
}

function transform(context) {
Object.keys(context).forEach((i) => {
keys(context).forEach((i) => {
context[i] = context[i].toString()
})

Expand Down
34 changes: 17 additions & 17 deletions src/events/http/HttpServer.js
Expand Up @@ -30,6 +30,7 @@ import {
import LambdaProxyIntegrationEventV2 from './lambda-events/LambdaProxyIntegrationEventV2.js'

const { parse, stringify } = JSON
const { assign, entries, keys } = Object

export default class HttpServer {
#lambda = null
Expand Down Expand Up @@ -170,7 +171,7 @@ export default class HttpServer {
}

// Override default headers with headers that have been explicitly set
Object.keys(explicitlySetHeaders).forEach((key) => {
keys(explicitlySetHeaders).forEach((key) => {
const value = explicitlySetHeaders[key]
if (value) {
response.headers[key] = value
Expand Down Expand Up @@ -384,7 +385,7 @@ export default class HttpServer {
if (typeof endpoint.authorizer === 'string') {
authorizerOptions.name = authFunctionName
} else {
Object.assign(authorizerOptions, endpoint.authorizer)
assign(authorizerOptions, endpoint.authorizer)
}

// Create a unique scheme per endpoint
Expand Down Expand Up @@ -886,7 +887,7 @@ export default class HttpServer {
}
}

for (const [key, value] of Object.entries(endpoint.responses)) {
for (const [key, value] of entries(endpoint.responses)) {
if (
key !== 'default' &&
errorMessage.match(`^${value.selectionPattern || key}$`)
Expand All @@ -909,7 +910,7 @@ export default class HttpServer {
const { responseParameters } = chosenResponse

if (responseParameters) {
const responseParametersKeys = Object.keys(responseParameters)
const responseParametersKeys = keys(responseParameters)

if (this.log) {
this.log.debug('_____ RESPONSE PARAMETERS PROCCESSING _____')
Expand All @@ -922,7 +923,7 @@ export default class HttpServer {
}

// responseParameters use the following shape: "key": "value"
Object.entries(responseParameters).forEach(([key, value]) => {
entries(responseParameters).forEach(([key, value]) => {
const keyArray = key.split('.') // eg: "method.response.header.location"
const valueArray = value.split('.') // eg: "integration.response.body.redirect.url"

Expand Down Expand Up @@ -1034,7 +1035,7 @@ export default class HttpServer {
const endpointResponseHeaders =
(endpoint.response && endpoint.response.headers) || {}

Object.entries(endpointResponseHeaders)
entries(endpointResponseHeaders)
.filter(
([, value]) => typeof value === 'string' && /^'.*?'$/.test(value),
)
Expand All @@ -1046,7 +1047,7 @@ export default class HttpServer {
const { responseTemplates } = chosenResponse

if (typeof responseTemplates === 'object') {
const responseTemplatesKeys = Object.keys(responseTemplates)
const responseTemplatesKeys = keys(responseTemplates)

if (responseTemplatesKeys.length) {
// BAD IMPLEMENTATION: first key in responseTemplates
Expand Down Expand Up @@ -1124,7 +1125,7 @@ export default class HttpServer {
response.source = Buffer.from(result, 'base64')
response.variety = 'buffer'
} else if (typeof result === 'string') {
response.source = JSON.stringify(result)
response.source = stringify(result)
} else if (result && result.body && typeof result.body !== 'string') {
return this._reply502(
response,
Expand All @@ -1142,8 +1143,7 @@ export default class HttpServer {
endpoint.payload === '2.0' &&
(typeof result === 'string' || !result.statusCode)
) {
const body =
typeof result === 'string' ? result : JSON.stringify(result)
const body = typeof result === 'string' ? result : stringify(result)
result = {
isBase64Encoded: false,
statusCode: 200,
Expand All @@ -1164,14 +1164,14 @@ export default class HttpServer {

const headers = {}
if (result && result.headers) {
Object.keys(result.headers).forEach((header) => {
keys(result.headers).forEach((header) => {
headers[header] = (headers[header] || []).concat(
result.headers[header],
)
})
}
if (result && result.multiValueHeaders) {
Object.keys(result.multiValueHeaders).forEach((header) => {
keys(result.multiValueHeaders).forEach((header) => {
headers[header] = (headers[header] || []).concat(
result.multiValueHeaders[header],
)
Expand All @@ -1193,7 +1193,7 @@ export default class HttpServer {
})
}

Object.keys(headers).forEach((header) => {
keys(headers).forEach((header) => {
if (header.toLowerCase() === 'set-cookie') {
headers[header].forEach(parseCookies)
} else {
Expand All @@ -1219,7 +1219,7 @@ export default class HttpServer {
})

if (typeof result === 'string') {
response.source = JSON.stringify(result)
response.source = stringify(result)
} else if (result && typeof result.body !== 'undefined') {
if (result.isBase64Encoded) {
response.encoding = 'binary'
Expand Down Expand Up @@ -1313,7 +1313,7 @@ export default class HttpServer {

const resourceRoutes = parseResources(this.#serverless.service.resources)

if (!resourceRoutes || !Object.keys(resourceRoutes).length) {
if (!resourceRoutes || !keys(resourceRoutes).length) {
return
}

Expand All @@ -1326,7 +1326,7 @@ export default class HttpServer {
serverlessLog('Routes defined in resources:')
}

Object.entries(resourceRoutes).forEach(([methodId, resourceRoutesObj]) => {
entries(resourceRoutes).forEach(([methodId, resourceRoutesObj]) => {
const { isProxy, method, pathResource, proxyUri } = resourceRoutesObj

if (!isProxy) {
Expand Down Expand Up @@ -1416,7 +1416,7 @@ export default class HttpServer {
const { params } = request
let resultUri = proxyUriInUse

Object.entries(params).forEach(([key, value]) => {
entries(params).forEach(([key, value]) => {
resultUri = resultUri.replace(`{${key}}`, value)
})

Expand Down
6 changes: 4 additions & 2 deletions src/events/http/createJWTAuthScheme.js
Expand Up @@ -2,6 +2,8 @@ import Boom from '@hapi/boom'
import jwt from 'jsonwebtoken'
import serverlessLog from '../../serverlessLog.js'

const { isArray } = Array

export default function createAuthScheme(jwtOptions, { log }) {
const authorizerName = jwtOptions.name

Expand Down Expand Up @@ -64,10 +66,10 @@ export default function createAuthScheme(jwtOptions, { log }) {
return Boom.unauthorized('JWT Token not from correct issuer url')
}

const validAudiences = Array.isArray(jwtOptions.audience)
const validAudiences = isArray(jwtOptions.audience)
? jwtOptions.audience
: [jwtOptions.audience]
const providedAudiences = Array.isArray(aud) ? aud : [aud]
const providedAudiences = isArray(aud) ? aud : [aud]
const validAudienceProvided = providedAudiences.some((a) =>
validAudiences.includes(a),
)
Expand Down
22 changes: 10 additions & 12 deletions src/events/http/lambda-events/LambdaProxyIntegrationEventV2.js
Expand Up @@ -6,9 +6,9 @@ import {
parseHeaders,
} from '../../../utils/index.js'

const { byteLength } = Buffer
const { isArray } = Array
const { parse } = JSON
const { assign } = Object
const { assign, entries, fromEntries } = Object

// https://www.serverless.com/framework/docs/providers/aws/events/http-api/
// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
Expand Down Expand Up @@ -102,7 +102,7 @@ export default class LambdaProxyIntegrationEventV2 {
body instanceof Buffer ||
body instanceof ArrayBuffer)
) {
headers['Content-Length'] = String(byteLength(body))
headers['Content-Length'] = String(Buffer.byteLength(body))
}

// Set a default Content-Type if not provided.
Expand Down Expand Up @@ -155,14 +155,12 @@ export default class LambdaProxyIntegrationEventV2 {
const requestTime = formatToClfTime(received)
const requestTimeEpoch = received

const cookies = Object.entries(this.#request.state).flatMap(
([key, value]) => {
if (Array.isArray(value)) {
return value.map((v) => `${key}=${v}`)
}
return `${key}=${value}`
},
)
const cookies = entries(this.#request.state).flatMap(([key, value]) => {
if (isArray(value)) {
return value.map((v) => `${key}=${v}`)
}
return `${key}=${value}`
})

return {
version: '2.0',
Expand All @@ -172,7 +170,7 @@ export default class LambdaProxyIntegrationEventV2 {
cookies,
headers,
queryStringParameters: this.#request.url.search
? Object.fromEntries(Array.from(this.#request.url.searchParams))
? fromEntries(Array.from(this.#request.url.searchParams))
: null,
requestContext: {
accountId: 'offlineContext_accountId',
Expand Down
7 changes: 4 additions & 3 deletions src/events/http/lambda-events/renderVelocityTemplateObject.js
@@ -1,14 +1,15 @@
import { Compile, parse } from 'velocityjs'
import { Compile, parse as velocityParse } from 'velocityjs'
import runInPollutedScope from '../javaHelpers.js'
import debugLog from '../../../debugLog.js'
import { isPlainObject } from '../../../utils/index.js'

const { parse } = JSON
const { entries } = Object

function tryToParseJSON(string) {
let parsed
try {
parsed = JSON.parse(string)
parsed = parse(string)
} catch (err) {
// nothing! Some things are not meant to be parsed.
}
Expand All @@ -24,7 +25,7 @@ function renderVelocityString(velocityString, context, v3Utils) {
// Quick args explanation:
// { escape: false } --> otherwise would escape &, < and > chars with html (&amp;, &lt; and &gt;)
// render(context, null, true) --> null: no custom macros; true: silent mode, just like APIG
new Compile(parse(velocityString), { escape: false }).render(
new Compile(velocityParse(velocityString), { escape: false }).render(
context,
null,
true,
Expand Down
4 changes: 3 additions & 1 deletion src/lambda/Lambda.js
@@ -1,6 +1,8 @@
import HttpServer from './HttpServer.js'
import LambdaFunctionPool from './LambdaFunctionPool.js'

const { assign } = Object

export default class Lambda {
#httpServer = null
#lambdas = new Map()
Expand Down Expand Up @@ -51,7 +53,7 @@ export default class Lambda {

listFunctionNamePairs() {
const funcNamePairs = Array.from(this.#lambdaFunctionNamesKeys).reduce(
(obj, [key, value]) => Object.assign(obj, { [key]: value }), // Be careful! Maps can have non-String keys; object literals can't.
(obj, [key, value]) => assign(obj, { [key]: value }), // Be careful! Maps can have non-String keys; object literals can't.
{},
)
return funcNamePairs
Expand Down
5 changes: 2 additions & 3 deletions src/lambda/handler-runner/docker-runner/DockerContainer.js
Expand Up @@ -13,8 +13,7 @@ import debugLog from '../../../debugLog.js'
import { logLayers, logWarning } from '../../../serverlessLog.js'

const { stringify } = JSON
const { entries } = Object
const { keys } = Object
const { entries, keys } = Object

export default class DockerContainer {
#containerId = null
Expand Down Expand Up @@ -478,7 +477,7 @@ export default class DockerContainer {
_getLayersSha256() {
return crypto
.createHash('sha256')
.update(JSON.stringify(this.#layers))
.update(stringify(this.#layers))
.digest('hex')
}

Expand Down
24 changes: 13 additions & 11 deletions src/lambda/handler-runner/in-process-runner/InProcessRunner.js
@@ -1,14 +1,16 @@
import { performance } from 'perf_hooks'
import * as path from 'path'
import * as fs from 'fs'
import { readdirSync } from 'fs'
import { dirname, resolve } from 'path'

const { assign, keys } = Object

const clearModule = (fP, opts) => {
const options = opts ?? {}
let filePath = fP
if (!require.cache[filePath]) {
const dirname = path.dirname(filePath)
for (const fn of fs.readdirSync(dirname)) {
const fullPath = path.resolve(dirname, fn)
const dirName = dirname(filePath)
for (const fn of readdirSync(dirName)) {
const fullPath = resolve(dirName, fn)
if (
fullPath.substr(0, filePath.length + 1) === `${filePath}.` &&
require.cache[fullPath]
Expand Down Expand Up @@ -47,7 +49,7 @@ const clearModule = (fP, opts) => {
let cleanup = false
do {
cleanup = false
for (const fn of Object.keys(require.cache)) {
for (const fn of keys(require.cache)) {
if (
require.cache[fn] &&
require.cache[fn].id !== '.' &&
Expand Down Expand Up @@ -111,7 +113,7 @@ export default class InProcessRunner {
// NOTE: Don't use Object spread (...) here!
// otherwise the values of the attached props are not coerced to a string
// e.g. process.env.foo = 1 should be coerced to '1' (string)
Object.assign(process.env, this.#env)
assign(process.env, this.#env)

// lazy load handler with first usage
if (!this.#allowCache) {
Expand Down Expand Up @@ -146,17 +148,17 @@ export default class InProcessRunner {

let callback

const callbackCalled = new Promise((resolve, reject) => {
const callbackCalled = new Promise((res, rej) => {
callback = (err, data) => {
if (err === 'Unauthorized') {
resolve('Unauthorized')
res('Unauthorized')
return
}
if (err) {
reject(err)
rej(err)
return
}
resolve(data)
res(data)
}
})

Expand Down

0 comments on commit ed9d6cd

Please sign in to comment.