Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update nodejs express serverless function template #13176

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import {
addRestApi,
createNewProjectDir,
deleteProject,
deleteProjectDir,
initJSProjectWithProfile,
amplifyPushAuth,
addFunction,
getProjectMeta,
} from '@aws-amplify/amplify-e2e-core';
import fetch from 'node-fetch';
import { v4 as uuid } from 'uuid';

const projName = 'apigwexpresstest';
const [shortId] = uuid().split('-');
const apiName = `expressapi${shortId}`;

describe('API Gateway Express e2e test', () => {
let projRoot: string;
beforeEach(async () => {
projRoot = await createNewProjectDir(projName);
await initJSProjectWithProfile(projRoot, { name: projName });
await addFunction(projRoot, { functionTemplate: 'Serverless ExpressJS function (Integration with API Gateway)' }, 'nodejs');
await addRestApi(projRoot, { apiName: apiName, existingLambda: true });
await amplifyPushAuth(projRoot);
});

afterEach(async () => {
await deleteProject(projRoot);
deleteProjectDir(projRoot);
});

it(' curd requests to api gateway ', async () => {
const projMeta = getProjectMeta(projRoot);
expect(projMeta.api).toBeDefined();
const apiPath = projMeta?.api?.[apiName]?.output?.RootUrl;
expect(apiPath).toBeDefined();
const apiResource = `${apiPath}/items`;

// GET request
const resGet = await fetch(apiResource);
Dismissed Show dismissed Hide dismissed
expect(resGet.status).toEqual(200);
await resGet.json().then((data) => {
expect(data.success).toEqual('get call succeed!');
});

// POST request
const resPost = await fetch(apiResource, {
Dismissed Show dismissed Hide dismissed
method: 'POST',
body: JSON.stringify({ msg: 'hello' }),
headers: { 'Content-Type': 'application/json' },
});
expect(resPost.status).toEqual(200);
await resPost.json().then((data) => {
expect(data.success).toEqual('post call succeed!');
expect(data.body.msg).toEqual('hello');
});

// PUT request
const resPut = await fetch(apiResource, {
Dismissed Show dismissed Hide dismissed
method: 'PUT',
body: JSON.stringify({ msg: 'hello' }),
headers: { 'Content-Type': 'application/json' },
});
expect(resPut.status).toEqual(200);
await resPut.json().then((data) => {
expect(data.success).toEqual('put call succeed!');
expect(data.body.msg).toEqual('hello');
});

// DELETE request
const resDelete = await fetch(apiResource, {
Dismissed Show dismissed Hide dismissed
method: 'DELETE',
body: JSON.stringify({ msg: 'hello' }),
headers: { 'Content-Type': 'application/json' },
});
expect(resDelete.status).toEqual(200);
await resDelete.json().then((data) => {
expect(data.success).toEqual('delete call succeed!');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,12 @@ See the License for the specific language governing permissions and limitations

<%= props.topLevelComment %>

const express = require('express')
const bodyParser = require('body-parser')
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
const express = require('express');
const { getCurrentInvoke } = require("@vendia/serverless-express");

// declare a new express app
const app = express()
app.use(bodyParser.json())
app.use(awsServerlessExpressMiddleware.eventContext())
app.use(express.json())

// Enable CORS for all methods
app.use(function(req, res, next) {
Expand Down Expand Up @@ -46,12 +44,16 @@ app.get('<%= props.functionTemplate.parameters.expressPath %>/*', function(req,

app.post('<%= props.functionTemplate.parameters.expressPath %>', function(req, res) {
// Add your code here
res.json({success: 'post call succeed!', url: req.url, body: req.body})
const { event, context } = getCurrentInvoke();
const requestBody = JSON.parse(event.body);
res.json({ success: 'post call succeed!', url: req.url, body: requestBody });
});

app.post('<%= props.functionTemplate.parameters.expressPath %>/*', function(req, res) {
// Add your code here
res.json({success: 'post call succeed!', url: req.url, body: req.body})
const { event, context } = getCurrentInvoke();
const requestBody = JSON.parse(event.body);
res.json({ success: 'post call succeed!', url: req.url, body: requestBody });
});

/****************************
Expand All @@ -60,12 +62,16 @@ app.post('<%= props.functionTemplate.parameters.expressPath %>/*', function(req,

app.put('<%= props.functionTemplate.parameters.expressPath %>', function(req, res) {
// Add your code here
res.json({success: 'put call succeed!', url: req.url, body: req.body})
const { event, context } = getCurrentInvoke();
const requestBody = JSON.parse(event.body);
res.json({ success: 'put call succeed!', url: req.url, body: requestBody });
});

app.put('<%= props.functionTemplate.parameters.expressPath %>/*', function(req, res) {
// Add your code here
res.json({success: 'put call succeed!', url: req.url, body: req.body})
const { event, context } = getCurrentInvoke();
const requestBody = JSON.parse(event.body);
res.json({ success: 'put call succeed!', url: req.url, body: requestBody });
});

/****************************
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
{
"httpMethod": "POST",
"path": "/item",
"path": "/items",
"queryStringParameters": {
"limit": "10"
},
"headers": {
"Content-Type": "application/json"
},
"body": "{\"msg\":\"Hello from the event.json body\"}"
"body": "{'msg':'Hello from the event.json body'}",
"requestContext": {
"resourcePath": "/item",
"httpMethod": "POST"
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
const awsServerlessExpress = require('aws-serverless-express');
const serverlessExpress = require('@vendia/serverless-express');
const app = require('./app');

/**
* @type {import('http').Server}
*/
const server = awsServerlessExpress.createServer(app);

/**
* @type {import('@types/aws-lambda').APIGatewayProxyHandler}
*/
exports.handler = (event, context) => {
exports.handler = async (event, context) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise;
return serverlessExpress({ app })(event, context);
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
"main": "index.js",
"license": "Apache-2.0",
"dependencies": {
"aws-serverless-express": "^3.3.5",
"body-parser": "^1.17.1",
"@vendia/serverless-express": "^4.10.4",
"express": "^4.15.2"
},
"devDependencies": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export function provideServerless(): Promise<FunctionTemplateParameters> {
sourceRoot: pathToTemplateFiles,
sourceFiles: files,
parameters: {
path: '/item',
expressPath: '/item',
path: '/items',
expressPath: '/items',
},
defaultEditorFile: path.join('src', 'app.js'),
destMap: getDstMap(files),
Expand Down