Skip to content

Commit

Permalink
refactor(amplify-category-api): add api key with gql compiled
Browse files Browse the repository at this point in the history
  • Loading branch information
danielleadams committed Sep 9, 2021
1 parent 9e37538 commit 7077fc8
Show file tree
Hide file tree
Showing 6 changed files with 13 additions and 95 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jest.mock('../../../provider-utils/awscloudformation/utils/amplify-meta-utils',

jest.mock('amplify-cli-core');

const fs_mock = (fs as unknown) as jest.Mocked<typeof fs>;
const fs_mock = fs as unknown as jest.Mocked<typeof fs>;
const writeTransformerConfiguration_mock = writeTransformerConfiguration as jest.MockedFunction<typeof writeTransformerConfiguration>;
const getAppSyncResourceName_mock = getAppSyncResourceName as jest.MockedFunction<typeof getAppSyncResourceName>;
const getAppSyncAuthConfig_mock = getAppSyncAuthConfig as jest.MockedFunction<typeof getAppSyncAuthConfig>;
Expand Down Expand Up @@ -245,64 +245,3 @@ describe('update artifacts', () => {
expect(context_stub.print.warning.mock.calls.length).toBe(3);
});
});

describe('update artifacts without graphql compile', () => {
let cfnApiArtifactHandler: ApiArtifactHandler;
let updateRequestStub: UpdateApiRequest;
const updateRequestStubBase: UpdateApiRequest = {
version: 1,
serviceModification: {
serviceName: 'AppSync',
},
};

beforeAll(() => {
getAppSyncResourceName_mock.mockImplementation(() => testApiName);
getAppSyncAuthConfig_mock.mockImplementation(() => ({
defaultAuthentication: {
authenticationType: 'AMAZON_COGNITO_USER_POOLS',
userPoolConfig: {
userPoolId: 'myUserPoolId',
},
},
additionalAuthenticationProviders: [],
}));
});

beforeEach(() => {
jest.clearAllMocks();
updateRequestStub = _.cloneDeep(updateRequestStubBase);
cfnApiArtifactHandler = getCfnApiArtifactHandler(context_stub);
});

it('throws error if no GQL API in project', () => {
getAppSyncResourceName_mock.mockImplementationOnce(() => undefined);
return expect(cfnApiArtifactHandler.updateArtifactsWithoutCompile(updateRequestStub)).rejects.toMatchInlineSnapshot(
`[Error: No AppSync API configured in the project. Use 'amplify add api' to create an API.]`,
);
});

it('writes new schema if specified', async () => {
const newSchemaContents = 'a new schema';
updateRequestStub.serviceModification.transformSchema = newSchemaContents;
await cfnApiArtifactHandler.updateArtifactsWithoutCompile(updateRequestStub);
expect(fs_mock.writeFileSync.mock.calls.length).toBe(1);
expect(fs_mock.writeFileSync.mock.calls[0][1]).toBe(newSchemaContents);
});

it('updates resolver config if not empty', async () => {
updateRequestStub.serviceModification.conflictResolution = {
defaultResolutionStrategy: {
type: 'OPTIMISTIC_CONCURRENCY',
},
};
await cfnApiArtifactHandler.updateArtifactsWithoutCompile(updateRequestStub);
expect(writeTransformerConfiguration_mock.mock.calls.length).toBe(1);
});

it('updates meta files after update', async () => {
await cfnApiArtifactHandler.updateArtifactsWithoutCompile(updateRequestStub);
expect(context_stub.amplify.updateamplifyMetaAfterResourceUpdate.mock.calls.length).toBe(1);
expect(context_stub.amplify.updateBackendConfigAfterResourceUpdate.mock.calls.length).toBe(1);
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import chalk from 'chalk';
import { $TSContext } from 'amplify-cli-core';
import * as prompts from 'amplify-prompts';
import { promptToAddApiKey } from '../../../provider-utils/awscloudformation/prompt-to-add-api-key';
import * as walkthrough from '../../../provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough';
import * as cfnApiArtifactHandler from '../../../provider-utils/awscloudformation/cfn-api-artifact-handler';
Expand All @@ -10,10 +10,16 @@ jest.mock('../../../provider-utils/awscloudformation/service-walkthroughs/appSyn

jest.mock('../../../provider-utils/awscloudformation/cfn-api-artifact-handler', () => ({
getCfnApiArtifactHandler: jest.fn(() => {
return { updateArtifactsWithoutCompile: jest.fn() };
return { updateArtifacts: jest.fn() };
}),
}));

jest.mock('amplify-prompts', () => ({
prompter: {
confirmContinue: jest.fn().mockImplementation(() => true),
},
}));

describe('prompt to add Api Key', () => {
it('runs through expected user flow: print info, update files', async () => {
const envName = 'envone';
Expand All @@ -23,18 +29,15 @@ describe('prompt to add Api Key', () => {
return { envName };
},
},
prompt: {
confirm: jest.fn(() => true),
},
} as unknown as $TSContext;

jest.spyOn(ctx.prompt, 'confirm');
jest.spyOn(prompts.prompter, 'confirmContinue');
jest.spyOn(walkthrough, 'askApiKeyQuestions');
jest.spyOn(cfnApiArtifactHandler, 'getCfnApiArtifactHandler');

await promptToAddApiKey(ctx);

expect(ctx.prompt.confirm).toHaveBeenCalledWith('Would you like to create an API Key?', true);
expect(prompts.prompter.confirmContinue).toHaveBeenCalledWith('Would you like to create an API Key?');
expect(walkthrough.askApiKeyQuestions).toHaveBeenCalledTimes(1);
expect(cfnApiArtifactHandler.getCfnApiArtifactHandler).toHaveBeenCalledTimes(1);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@ import { AddApiRequest, UpdateApiRequest } from 'amplify-headless-interface';
export interface ApiArtifactHandler {
createArtifacts(request: AddApiRequest): Promise<string>;
updateArtifacts(request: UpdateApiRequest): Promise<void>;
updateArtifactsWithoutCompile(request: UpdateApiRequest): Promise<void>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,30 +143,6 @@ class CfnApiArtifactHandler implements ApiArtifactHandler {
printApiKeyWarnings(this.context, oldConfigHadApiKey, authConfigHasApiKey(authConfig));
};

updateArtifactsWithoutCompile = async (request: UpdateApiRequest): Promise<void> => {
const updates = request.serviceModification;
const apiName = getAppSyncResourceName(this.context.amplify.getProjectMeta());
if (!apiName) {
throw new Error(`No AppSync API configured in the project. Use 'amplify add api' to create an API.`);
}
const resourceDir = this.getResourceDir(apiName);
if (updates.transformSchema) {
this.writeSchema(resourceDir, updates.transformSchema);
}
if (updates.conflictResolution) {
updates.conflictResolution = await this.createResolverResources(updates.conflictResolution);
await writeResolverConfig(updates.conflictResolution, resourceDir);
}
const authConfig = getAppSyncAuthConfig(this.context.amplify.getProjectMeta());

if (updates.defaultAuthType) authConfig.defaultAuthentication = appSyncAuthTypeToAuthConfig(updates.defaultAuthType);
if (updates.additionalAuthTypes)
authConfig.additionalAuthenticationProviders = updates.additionalAuthTypes.map(appSyncAuthTypeToAuthConfig);

this.context.amplify.updateamplifyMetaAfterResourceUpdate(category, apiName, 'output', { authConfig });
this.context.amplify.updateBackendConfigAfterResourceUpdate(category, apiName, 'output', { authConfig });
};

private writeSchema = (resourceDir: string, schema: string) => {
fs.writeFileSync(path.join(resourceDir, gqlSchemaFilename), schema);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export async function promptToAddApiKey(context: $TSContext): Promise<void> {
const apiKeyConfig = await askApiKeyQuestions();
const authConfig = [apiKeyConfig];

await getCfnApiArtifactHandler(context).updateArtifactsWithoutCompile({
await getCfnApiArtifactHandler(context).updateArtifacts({
version: 1,
serviceModification: {
serviceName: 'AppSync',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ directive @aws_api_key on FIELD_DEFINITION | OBJECT
directive @aws_iam on FIELD_DEFINITION | OBJECT
directive @aws_oidc on FIELD_DEFINITION | OBJECT
directive @aws_cognito_user_pools(cognito_groups: [String!]) on FIELD_DEFINITION | OBJECT
directive @allow_public_data_access_with_api_key(in: [String!]) on OBJECT
# Allows transformer libraries to deprecate directive arguments.
directive @deprecated(reason: String) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION | ENUM | ENUM_VALUE
Expand Down

0 comments on commit 7077fc8

Please sign in to comment.