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

Throw an error for unsupported categories in Gen2 #13938

Merged
merged 9 commits into from
Sep 25, 2024
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
4 changes: 3 additions & 1 deletion packages/amplify-gen2-codegen/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export type AuthLambdaTriggers = Record<AuthTriggerEvents, Lambda>;
export type AuthTriggerEvents = 'createAuthChallenge' | 'customMessage' | 'defineAuthChallenge' | 'postAuthentication' | 'postConfirmation' | 'preAuthentication' | 'preSignUp' | 'preTokenGeneration' | 'userMigration' | 'verifyAuthChallengeResponse';

// @public (undocumented)
export const createGen2Renderer: ({ outputDir, appId, backendEnvironmentName, auth, storage, data, functions, fileWriter, }: Readonly<Gen2RenderingOptions>) => Renderer;
export const createGen2Renderer: ({ outputDir, appId, backendEnvironmentName, auth, storage, data, functions, unsupportedCategories, fileWriter, }: Readonly<Gen2RenderingOptions>) => Renderer;

// @public (undocumented)
export type CustomAttribute = {
Expand Down Expand Up @@ -118,6 +118,8 @@ export interface Gen2RenderingOptions {
outputDir: string;
// (undocumented)
storage?: StorageRenderParameters;
// (undocumented)
unsupportedCategories?: Map<string, string>;
}

// @public (undocumented)
Expand Down
28 changes: 28 additions & 0 deletions packages/amplify-gen2-codegen/src/backend/synthesizer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,34 @@ describe('BackendRenderer', () => {
assert(!output.includes('cfnUserPoolClient'));
});
});
describe('errors for unsupported categories', () => {
it('Renders error statement if unsupported categories are present', () => {
const renderer = new BackendSynthesizer();
const rendered = renderer.render({
unsupportedCategories: new Map([
['rest api', 'https://docs.amplify.aws/react/build-a-backend/add-aws-services/rest-api/'],
['geo', 'https://docs.amplify.aws/react/build-a-backend/add-aws-services/geo/'],
['predictions', 'https://docs.amplify.aws/react/build-a-backend/add-aws-services/predictions/'],
]),
});
const output = printNodeArray(rendered);
assert(
output.includes(
'throw new Error("Category rest api is unsupported, please follow https://docs.amplify.aws/react/build-a-backend/add-aws-services/rest-api/")',
),
);
assert(
output.includes(
'throw new Error("Category geo is unsupported, please follow https://docs.amplify.aws/react/build-a-backend/add-aws-services/geo/")',
),
);
assert(
output.includes(
'throw new Error("Category predictions is unsupported, please follow https://docs.amplify.aws/react/build-a-backend/add-aws-services/predictions/")',
),
);
});
});
describe('imports', () => {
for (const resource of ['storage', 'data', 'auth']) {
describe(resource, () => {
Expand Down
24 changes: 23 additions & 1 deletion packages/amplify-gen2-codegen/src/backend/synthesizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export interface BackendRenderParameters {
importFrom: string;
functionNamesAndCategories: Map<string, string>;
};
unsupportedCategories?: Map<string, string>;
}

export class BackendSynthesizer {
Expand Down Expand Up @@ -114,6 +115,7 @@ export class BackendSynthesizer {
const backendFunctionIdentifier = factory.createIdentifier('defineBackend');

const imports = [];
const errors: ts.CallExpression[] = [];
const defineBackendProperties = [];
const nodes = [];

Expand Down Expand Up @@ -170,6 +172,26 @@ export class BackendSynthesizer {

imports.push(this.createImportStatement([backendFunctionIdentifier], '@aws-amplify/backend'));

if (renderArgs.unsupportedCategories) {
const categories = renderArgs.unsupportedCategories;

for (const [key, value] of categories) {
if (key == 'custom') {
errors.push(
factory.createCallExpression(factory.createIdentifier('throw new Error'), undefined, [
factory.createStringLiteral(`Category ${key} has changed, learn more ${value}`),
]),
);
} else {
errors.push(
factory.createCallExpression(factory.createIdentifier('throw new Error'), undefined, [
factory.createStringLiteral(`Category ${key} is unsupported, please follow ${value}`),
]),
);
}
}
}

const callBackendFn = this.defineBackendCall(backendFunctionIdentifier, defineBackendProperties);
const backendVariable = factory.createVariableDeclaration('backend', undefined, undefined, callBackendFn);
const backendStatement = factory.createVariableStatement(
Expand Down Expand Up @@ -323,6 +345,6 @@ export class BackendSynthesizer {
),
);
}
return factory.createNodeArray([...imports, backendStatement, ...nodes], true);
return factory.createNodeArray([...imports, ...errors, backendStatement, ...nodes], true);
}
}
6 changes: 6 additions & 0 deletions packages/amplify-gen2-codegen/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export interface Gen2RenderingOptions {
storage?: StorageRenderParameters;
data?: DataDefinition;
functions?: FunctionDefinition[];
unsupportedCategories?: Map<string, string>;
fileWriter?: (content: string, path: string) => Promise<void>;
}
const createFileWriter = (path: string) => async (content: string) => fs.writeFile(path, content);
Expand All @@ -65,6 +66,7 @@ export const createGen2Renderer = ({
storage,
data,
functions,
unsupportedCategories,
fileWriter = (content, path) => createFileWriter(path)(content),
}: Readonly<Gen2RenderingOptions>): Renderer => {
const ensureOutputDir = new EnsureDirectory(outputDir);
Expand Down Expand Up @@ -100,6 +102,10 @@ export const createGen2Renderer = ({

const renderers: Renderer[] = [ensureOutputDir, ensureAmplifyDirectory, amplifyPackageJson, amplifyTsConfigJson, jsonRenderer];

if (unsupportedCategories && unsupportedCategories.size >= 1) {
backendRenderOptions.unsupportedCategories = unsupportedCategories;
}

if (functions && functions.length) {
const functionNamesAndCategory = new Map<string, string>();
for (const func of functions) {
Expand Down
40 changes: 40 additions & 0 deletions packages/amplify-migration/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const generateGen2Code = async ({
storage: await storageDefinitionFetcher.getDefinition(),
data: await dataDefinitionFetcher.getDefinition(),
functions: await functionsDefinitionFetcher.getDefinition(),
unsupportedCategories: unsupportedCategories(),
};

const pipeline = createGen2Renderer(gen2RenderOptions);
Expand Down Expand Up @@ -118,6 +119,44 @@ const resolveAppId = (): string => {
return meta?.providers?.awscloudformation?.AmplifyAppId;
};

const unsupportedCategories = (): Map<string, string> => {
const unsupportedCategories = new Map<string, string>();
const urlPrefix = 'https://docs.amplify.aws/react/build-a-backend/add-aws-services';

unsupportedCategories.set('geo', `${urlPrefix}/geo/`);
unsupportedCategories.set('analytics', `${urlPrefix}/analytics/`);
unsupportedCategories.set('predictions', `${urlPrefix}/predictions/`);
unsupportedCategories.set('notifications', `${urlPrefix}/in-app-messaging/`);
unsupportedCategories.set('interactions', `${urlPrefix}/interactions/`);
unsupportedCategories.set('custom', `${urlPrefix}/custom-resources/`);
unsupportedCategories.set('rest api', `${urlPrefix}/rest-api/`);

const meta = stateManager.getMeta();
const categories = Object.keys(meta);

const unsupportedCategoriesList = new Map<string, string>();

categories.forEach((category) => {
if (category == 'api') {
const apiList = meta?.api;
if (apiList) {
Object.keys(apiList).forEach((api) => {
const apiObj = apiList[api];
if (apiObj.service == 'API Gateway') {
unsupportedCategoriesList.set('rest api', unsupportedCategories.get('rest api')!);
}
});
}
} else {
if (unsupportedCategories.has(category)) {
unsupportedCategoriesList.set(category, unsupportedCategories.get(category)!);
}
}
});

return unsupportedCategoriesList;
};

export async function execute() {
const amplifyClient = new AmplifyClient();
const s3Client = new S3Client();
Expand All @@ -132,6 +171,7 @@ export async function execute() {
const amplifyStackParser = new AmplifyStackParser(cloudFormationClient);
const backendEnvironmentResolver = new BackendEnvironmentResolver(appId, amplifyClient);
const backendEnvironment = await backendEnvironmentResolver.selectBackendEnvironment();

await generateGen2Code({
outputDirectory: TEMP_GEN_2_OUTPUT_DIR,
storageDefinitionFetcher: new AppStorageDefinitionFetcher(backendEnvironmentResolver, new BackendDownloader(s3Client), s3Client),
Expand Down
Loading