Skip to content

Commit

Permalink
fix: support adding REST API paths in 'add api' (aws-amplify#7229)
Browse files Browse the repository at this point in the history
  • Loading branch information
cjihrig authored and cjihrig-aws committed Jul 12, 2021
1 parent c5cd26f commit 607b741
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 4 deletions.
33 changes: 32 additions & 1 deletion packages/amplify-category-api/src/commands/api/add.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const inquirer = require('inquirer');
const subcommand = 'add';
const category = 'api';
const apiGatewayService = 'API Gateway';

let options;

Expand All @@ -10,7 +12,7 @@ module.exports = {
const servicesMetadata = require('../../provider-utils/supported-services').supportedServices;
return amplify
.serviceSelectionPrompt(context, category, servicesMetadata)
.then(result => {
.then(async result => {
options = {
service: result.service,
providerPlugin: result.providerName,
Expand All @@ -21,6 +23,10 @@ module.exports = {
return;
}

if ((await shouldUpdateExistingRestApi(context, result.service)) === true) {
return providerController.updateResource(context, category, result.service, { allowContainers: false });
}

return providerController.addResource(context, category, result.service, options);
})
.then(resourceName => {
Expand All @@ -42,3 +48,28 @@ module.exports = {
});
},
};

async function shouldUpdateExistingRestApi(context, selectedService) {
if (selectedService !== apiGatewayService) {
return false;
}

const { allResources } = await context.amplify.getResourceStatus();
const hasRestApis = allResources.some(resource => resource.service === apiGatewayService && resource.mobileHubMigrated !== true);

if (!hasRestApis) {
return false;
}

const question = [
{
name: 'update',
message: 'Would you like to add a new path to an existing REST API:',
type: 'confirm',
default: true,
},
];
const answer = await inquirer.prompt(question);

return answer.update;
}
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,10 @@ async function isRestContainer(context) {
}

export async function updateResource(context, category, service, options) {
const allowContainers = options?.allowContainers ?? true;
let useContainerResource = false;
let apiType = API_TYPE.GRAPHQL;
if (isContainersEnabled(context)) {
if (allowContainers && isContainersEnabled(context)) {
const {
hasAPIGatewayContainerResource,
hasAPIGatewayLambdaResource,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export async function updateWalkthrough(context, defaultValuesFilename) {
name: 'operation',
message: 'What would you like to do',
type: 'list',
when: context.input.command !== 'add',
choices: [
{ name: 'Add another path', value: 'add' },
{ name: 'Update path', value: 'update' },
Expand All @@ -76,6 +77,12 @@ export async function updateWalkthrough(context, defaultValuesFilename) {

const updateApi = await inquirer.prompt(question);

// Inquirer does not currently support combining 'when' and 'default', so
// manually set the operation if the user ended up here via amplify api add.
if (context.input.command === 'add') {
updateApi.operation = 'add';
}

if (updateApi.resourceName === 'AdminQueries') {
const errMessage = `The Admin Queries API is maintained through the Auth category and should be updated using 'amplify update auth' command`;
context.print.warning(errMessage);
Expand Down
38 changes: 37 additions & 1 deletion packages/amplify-e2e-core/src/categories/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,10 +259,46 @@ export function addRestApi(cwd: string, settings: any) {
if (!('existingLambda' in settings) && !('isCrud' in settings)) {
reject(new Error('Missing property in settings object in addRestApi()'));
} else {
const isFirstRestApi = settings.isFirstRestApi ?? true;
let chain = spawn(getCLIPath(), ['add', 'api'], { cwd, stripColors: true })
.wait('Please select from one of the below mentioned services')
.send(KEY_DOWN_ARROW)
.sendCarriageReturn() // REST
.sendCarriageReturn(); // REST

if (!isFirstRestApi) {
chain.wait('Would you like to add a new path to an existing REST API');

if (settings.path) {
chain
.sendConfirmYes()
.wait('Please select the REST API you would want to update')
.sendCarriageReturn() // Select the first REST API
.wait('Provide a path')
.sendLine(settings.path)
.wait('Choose a lambda source')
.send(KEY_DOWN_ARROW)
.sendCarriageReturn() // Existing lambda
.wait('Choose the Lambda function to invoke by this path')
.sendCarriageReturn() // Pick first one
.wait('Restrict API access')
.sendConfirmNo() // Do not restrict access
.wait('Do you want to add another path')
.sendConfirmNo() // Do not add another path
.sendEof()
.run((err: Error) => {
if (err) {
reject(err);
} else {
resolve();
}
});
return;
} else {
chain.sendConfirmNo();
}
}

chain
.wait('Provide a friendly name for your resource to be used as a label for this category in the project')
.sendCarriageReturn()
.wait('Provide a path')
Expand Down
12 changes: 11 additions & 1 deletion packages/amplify-e2e-tests/src/__tests__/api_2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,16 +393,18 @@ describe('amplify add api (REST)', () => {
allowGuestUsers: true,
});
await addRestApi(projRoot, {
isFirstRestApi: false,
existingLambda: true,
restrictAccess: true,
allowGuestUsers: true,
});
await addRestApi(projRoot, {
isFirstRestApi: false,
existingLambda: true,
restrictAccess: true,
allowGuestUsers: false,
});
await addRestApi(projRoot, { existingLambda: true });
await addRestApi(projRoot, { isFirstRestApi: false, existingLambda: true });
await updateAuthAddAdminQueries(projRoot);
await amplifyPushUpdate(projRoot);

Expand All @@ -427,4 +429,12 @@ describe('amplify add api (REST)', () => {
expect(unauthPolicies[i].PolicyName).toMatch(/PolicyAPIGWUnauth\d/);
}
});

it('adds a rest api and then adds a path to the existing api', async () => {
await initJSProjectWithProfile(projRoot, {});
await addFunction(projRoot, { functionTemplate: 'Hello World' }, 'nodejs');
await addRestApi(projRoot, { existingLambda: true });
await addRestApi(projRoot, { isFirstRestApi: false, existingLambda: true, path: '/newpath' });
await amplifyPushUpdate(projRoot);
});
});

0 comments on commit 607b741

Please sign in to comment.