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

fix: api containers on repushing does not fail #8416

Merged
merged 2 commits into from
Oct 12, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
Expand Up @@ -52,6 +52,7 @@ export type ContainersStackProps = Readonly<{
createCloudMapService?: boolean;
gitHubSourceActionInfo?: GitHubSourceActionInfo;
existingEcrRepositories: Set<string>;
currentStackName: string;
}>;
export abstract class ContainersStack extends cdk.Stack {
protected readonly vpcId: string;
Expand Down Expand Up @@ -240,6 +241,7 @@ export abstract class ContainersStack extends cdk.Stack {
taskPorts,
isInitialDeploy,
desiredCount,
currentStackName,
createCloudMapService,
} = this.props;

Expand Down Expand Up @@ -313,7 +315,7 @@ export abstract class ContainersStack extends cdk.Stack {
if (build) {
const logicalId = `${name}Repository`;

const repositoryName = `${this.envName}-${categoryName}-${apiName}-${name}`;
const repositoryName = `${currentStackName}-${categoryName}-${apiName}-${name}`;

if (this.props.existingEcrRepositories.has(repositoryName)) {
repository = ecr.Repository.fromRepositoryName(this, logicalId, repositoryName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ export async function generateContainersArtifacts(
isInitialDeploy,
desiredCount,
restrictAccess,
currentStackName: envName,
apiType,
exposedContainer,
secretsArns,
Expand Down
9 changes: 8 additions & 1 deletion packages/amplify-e2e-core/src/categories/api.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { getCLIPath, updateSchema, nspawn as spawn, KEY_DOWN_ARROW } from '..';
import * as fs from 'fs-extra';
import * as path from 'path';
import { selectRuntime, selectTemplate } from './lambda-function';
import { singleSelect, multiSelect } from '../utils/selectors';
import _ from 'lodash';
import { EOL } from 'os';
import { modifiedApi } from './resources/modified-api-index';

export function getSchemaPath(schemaName: string): string {
return `${__dirname}/../../../amplify-e2e-tests/schemas/${schemaName}`;
Expand Down Expand Up @@ -590,6 +592,11 @@ export function addRestContainerApiForCustomPolicies(projectDir: string, setting
.wait('Select which container is the entrypoint')
.sendCarriageReturn()
.wait('"amplify publish" will build all your local backend and frontend resources')
.run((err: Error) => err ? reject(err) : resolve());
.run((err: Error) => (err ? reject(err) : resolve()));
});
}

export function modifyRestAPI(projectDir: string, apiName: string) {
const indexFilePath = path.join(projectDir, 'amplify', 'backend', 'api', apiName, 'src', 'express', 'index.js');
fs.writeFileSync(indexFilePath, modifiedApi);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
export const modifiedApi = `const express = require("express");
const bodyParser = require('body-parser');
const port = process.env.PORT || 3001;

const {
addPostToDDB,
scanPostsFromDDB,
getPostFromDDB
} = require('./DynamoDBActions');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Enable CORS for all methods
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
});

const checkAuthRules = (req, res, next) => {
const jwt = req.header("Authorization") || "";

const [, jwtBody] = jwt.split(".");

const obj = JSON.parse(
jwtBody ? Buffer.from(jwtBody, "base64").toString("utf-8") : "{}"
);

//Customer can perform logic on JWT body
//console.log(obj);
next();

//Failure example:
// const err = new Error("Access denied");
// err.statusCode = 403;
// return next(err);
}

app.use(checkAuthRules);

app.get("/posts", async (req, res, next) => {

try {
const result = await scanPostsFromDDB();
res.contentType("application/json").send(result);
} catch (err) {
next(err);
}
});

app.get("/post", async (req, res, next) => {
console.log(req.query.id);

try {
const result = await getPostFromDDB(req.query.id);
res.contentType("application/json").send(result);
} catch (err) {
next(err);
}
});

app.post("/post", async (req, res, next) => {

try {
const result = await addPostToDDB(req.body);
res.contentType("application/json").send(result);
} catch (err) {
next(err);
}
});

app.put('/post', async(req, res, next) => {
return {};
});

app.use((req, res, next) => {

try {
const result = \`Please try GET on /posts, /post?id=xyz, or a POST to /post with JSON {\"id\":\"123\",\"title\":\"Fargate test\"}\`;
res.contentType("application/json").send(result);
} catch (err) {
next(err);
}
});

// Error middleware must be defined last
app.use((err, req, res, next) => {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500; // If err has no specified error code, set error code to 'Internal Server Error (500)'
res
.status(err.statusCode)
.json({ message: err.message })
.end();
});

app.listen(port, () => {
console.log('Example app listening at http://localhost:' + port);
});`;
14 changes: 14 additions & 0 deletions packages/amplify-e2e-tests/src/__tests__/containers-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
deleteProject,
deleteProjectDir,
initJSProjectWithProfile,
getProjectMeta,
modifyRestAPI,
} from 'amplify-e2e-core';
import fetch from 'node-fetch';
import { getAWSExports } from '../aws-exports/awsExports';
Expand Down Expand Up @@ -44,4 +46,16 @@ describe('amplify api add', () => {
const result = await (await fetch(`${endpoint}/images`)).text();
expect(result).toEqual('Processing images...');
});

it('init project, enable containers and add multicontainer api push, edit and push', async () => {
const envName = 'devtest';
await initJSProjectWithProfile(projRoot, { name: 'multicontainer', envName });
await setupAmplifyProject(projRoot);
await addRestContainerApi(projRoot);
await amplifyPushWithoutCodegen(projRoot);
const meta = await getProjectMeta(projRoot);
const apiName = Object.keys(meta['api'])[0];
modifyRestAPI(projRoot, apiName);
await amplifyPushWithoutCodegen(projRoot);
});
});