Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const middlewares = [
middleware.eventContext(),
/* get userId from event */ (req, res, next) => {
try {
req.userId = req.apiGateway.event.requestContext.authorizer.sub
} catch (err) {
req.userId = null
console.warn(err.stack || err)
}
next()
}
]
// Create a server for a API instance
const server = adapter.createServer(apiFactory(repo, middlewares))
module.exports.handler = (event, context, callback) => {
// NOTE: aws-serverless-express uses context.succeed, but AWS already
// deprecated it in favor of callback
const fakeContext = {
succeed: res => callback(null, res)
}
// Proxy the actual request
adapter.proxy(server, event, fakeContext)
}
exports.handler = (event, context, callback) => {
if (process.env.LAMBDA_DEBUG_LOG) {
console.log('LAMBDA EVENT', event)
}
if (!event.command) {
// default web server stuff
const app = require('./build/server/server/index')
const server = awsServerlessExpress.createServer(app.default)
const startTime = (context.getRemainingTimeInMillis ? context.getRemainingTimeInMillis() : 0)
const webResponse = awsServerlessExpress.proxy(server, event, context)
if (process.env.DEBUG_SCALING) {
const endTime = (context.getRemainingTimeInMillis ? context.getRemainingTimeInMillis() : 0)
// confusingly, we do start - end, instead of the reverse,
// because it's *remaining* time which counts down
if ((startTime - endTime) > 3000) { //3 seconds
console.log('SLOW_RESPONSE milliseconds:', startTime-endTime, event)
}
}
return webResponse
} else if (event.command === 'ping') {
// no-op ping to keep server active, where useful, e.g. Amazon Lambda.
callback()
} else {
// handle a custom command sent as an event
const awsServerlessExpress = require('aws-serverless-express');
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const exercises = require('./controllers/exercises');
const routines = require('./controllers/routines');
const workouts = require('./controllers/workouts');
const workoutsHistory = require('./controllers/workoutsHistory');
const app = express();
app.use(awsServerlessExpressMiddleware.eventContext());
app.use(cors({ exposedHeaders: 'X-Total-Count' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/exercises', exercises);
app.use('/routines', routines);
app.use('/workouts/history', workoutsHistory);
app.use('/workouts', workouts);
app.listen(3000, () => console.log('Listening on port 3000.')); // ignored by lambda
const server = awsServerlessExpress.createServer(app);
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);
import {isHostedOnAWS} from "../../utils/aws";
// XXX next.dev enables HMR, which we don't want if not in development mode, or when we are on AWS's infrastructure
const nextAppConfig = {
dev: !isHostedOnAWS() && process.env.NODE_ENV === 'development',
// dir: process.env.NODE_ENV === 'development' ? path.resolve(__dirname, '../../../.next') : '.', // XXX Attempt to fix Next.js app in "development" stage, which failed. Used a proxy instead.
// conf: require('../../../next.config.js')
};
const nextApp = next(nextAppConfig);
const nextProxy = nextApp.getRequestHandler(); // Requests handled by nextProxy will be handled by the Next.js app
const app = express();
app.use(compression()); // See https://github.com/expressjs/compression/issues/133
app.use(awsServerlessExpressMiddleware.eventContext());
// Routes
app.get('/ko', (req, res) => {
console.log('req from', req.protocol + '://' + req.get('host') + req.originalUrl);
res.json({
status: 'ko'
})
});
app.get('/event', (req, res) => {
console.log('req from', req.protocol + '://' + req.get('host') + req.originalUrl);
res.send(`<pre>${JSON.stringify(req.apiGateway.event, null, 2)}</pre>`)
});
app.get('/static/:filename', (req, res) => {
console.log('req from', req.protocol + '://' + req.get('host') + req.originalUrl);
// default routes
app.use('/', router);
// global 404 response when page is not found
app.use((req, res) => {
res.boom.notFound('requested page not found');
});
// catch all error handling
app.use((err, req, res, _next) => {
res.error = JSON.stringify(err, Object.getOwnPropertyNames(err));
return res.boom.badImplementation('Something broke!');
});
const server = awsServerlessExpress.createServer(app, null);
module.exports = {
app,
handler: (event, context) => awsServerlessExpress.proxy(server, event, context)
};
'use strict';
//
// exnternal modules
const express = require('express');
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
//
// microservice
const microservice = express();
microservice.use(awsServerlessExpressMiddleware.eventContext());
//
// routes
const basePath = '/notes';
microservice.get(basePath, (req, res) => {
res.status(200).send({ message: 'OK Deploy' });
});
microservice.post(basePath, (req, res) => {
res.status(201).send({ message: 'OK' });
});
microservice.put(basePath, (req, res) => {
res.status(200).send({ message: 'OK' });
});
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
const express = require('express');
const bodyParser = require('body-parser');
const AWS = require('aws-sdk');
const uuid = require('node-uuid');
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
// declare a new express app
const app = express();
app.use(awsServerlessExpressMiddleware.eventContext({ deleteHeaders: false }), bodyParser.json());
const PETS_TABLE_NAME = `${process.env.MOBILE_HUB_DYNAMIC_PREFIX}-pets`;
AWS.config.update({ region: process.env.REGION });
const UNAUTH = 'UNAUTH';
// The DocumentClient class allows us to interact with DynamoDB using normal objects.
// Documentation for the class is available here: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html
const dynamoDb = new AWS.DynamoDB.DocumentClient();
app.get('/items/pets', (req, res) => {
// performs a DynamoDB Query operation to extract all records for the cognitoIdentityId in the table
dynamoDb.query({
TableName: PETS_TABLE_NAME,
KeyConditions: {
'use strict';
//
// external modules
const awsServerlessExpress = require('aws-serverless-express');
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
//
// microservice
const microservice = require('./microservice/api');
microservice.use(awsServerlessExpressMiddleware.eventContext());
//
// exposed microservice
const microserviceServer = awsServerlessExpress.createServer(microservice);
module.exports.microservice = (event, context) => awsServerlessExpress.proxy(microserviceServer, event, context);
const mockContext = {
callbackWaitsForEmptyEventLoop: true,
functionName: 'testFunction',
functionVersion: '1',
invokedFunctionArn: 'arn',
memoryLimitInMB: '128',
awsRequestId: 'id',
logGroupName: 'group',
logStreamName: 'stream',
getRemainingTimeInMillis: () => 2000,
done: () => false,
fail: (error: any) => false,
succeed: (message: string) => false
};
awsServerlessExpress.proxy(server, mockEvent, mockContext);
awsServerlessExpress.proxy(server, mockEvent, mockContext, 'CALLBACK', () => {});
awsServerlessExpress.proxy(server, mockEvent, mockContext, 'CONTEXT_SUCCEED');
awsServerlessExpress.proxy(server, mockEvent, mockContext, 'PROMISE').promise.then((response: awsServerlessExpress.Response) => {}).catch(err => {});
functionVersion: '1',
invokedFunctionArn: 'arn',
memoryLimitInMB: '128',
awsRequestId: 'id',
logGroupName: 'group',
logStreamName: 'stream',
getRemainingTimeInMillis: () => 2000,
done: () => false,
fail: (error: any) => false,
succeed: (message: string) => false
};
awsServerlessExpress.proxy(server, mockEvent, mockContext);
awsServerlessExpress.proxy(server, mockEvent, mockContext, 'CALLBACK', () => {});
awsServerlessExpress.proxy(server, mockEvent, mockContext, 'CONTEXT_SUCCEED');
awsServerlessExpress.proxy(server, mockEvent, mockContext, 'PROMISE').promise.then((response: awsServerlessExpress.Response) => {}).catch(err => {});