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: codegen --apiId broken state #689

Merged
merged 6 commits into from
Sep 13, 2023
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
31 changes: 16 additions & 15 deletions packages/amplify-codegen/src/commands/generateStatementsAndType.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const generateTypes = require('./types');
const generateStatements = require('./statements');
const { loadConfig } = require('../codegen-config');
const constants = require('../constants');
const { ensureIntrospectionSchema, getAppSyncAPIDetails } = require('../utils');
const { ensureIntrospectionSchema, getAppSyncAPIDetails, getAppSyncAPIInfoFromProject } = require('../utils');
const path = require('path');
const fs = require('fs-extra');

Expand All @@ -17,41 +17,42 @@ async function generateStatementsAndTypes(context, forceDownloadSchema, maxDepth
withoutInit = true;
}

// Check if introspection schema exists
const schemaPath = ['schema.graphql', 'schema.json'].map(p => path.join(process.cwd(), p)).find(p => fs.existsSync(p));
if (withoutInit && !schemaPath) {
throw Error(
`Please download the schema.graphql or schema.json and place in ${process.cwd()} before adding codegen when not in an amplify project`
);
}

if (withoutInit) {
forceDownloadSchema = false;
}
const config = loadConfig(context, withoutInit);
const projects = config.getProjects();
if (!projects.length) {
throw new NoAppSyncAPIAvailableError(constants.ERROR_CODEGEN_NO_API_CONFIGURED);
}
const project = projects[0];
const schemaPath = ['schema.graphql', 'schema.json'].map(p => path.join(process.cwd(), p)).find(p => fs.existsSync(p));
if (withoutInit && !project && !schemaPath) {
throw Error(
`Please download the schema.graphql or schema.json and place in ${process.cwd()} before adding codegen when not in an amplify project`,
);
}

let apis = [];
if (!withoutInit) {
apis = getAppSyncAPIDetails(context);
} else {
const api = getAppSyncAPIInfoFromProject(context, project);
if (api) {
apis = [api];
}
}
if (!apis.length && !withoutInit) {
throw new NoAppSyncAPIAvailableError(constants.ERROR_CODEGEN_NO_API_META);
}
const project = projects[0];
const { frontend } = project.amplifyExtension;
let projectPath = process.cwd();
if (!withoutInit) {
({ projectPath } = context.amplify.getEnvInfo());
}

let downloadPromises;
if (!withoutInit) {
if (apis.length) {
downloadPromises = projects.map(
async cfg =>
await ensureIntrospectionSchema(context, join(projectPath, cfg.schema), apis[0], cfg.amplifyExtension.region, forceDownloadSchema)
await ensureIntrospectionSchema(context, join(projectPath, cfg.schema), apis[0], cfg.amplifyExtension.region, forceDownloadSchema),
);
await Promise.all(downloadPromises);
}
Expand Down
31 changes: 19 additions & 12 deletions packages/amplify-codegen/src/commands/statements.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@ const Ora = require('ora');

const { loadConfig } = require('../codegen-config');
const constants = require('../constants');
const { ensureIntrospectionSchema, getFrontEndHandler, getAppSyncAPIDetails, readSchemaFromFile } = require('../utils');
const {
ensureIntrospectionSchema,
getFrontEndHandler,
getAppSyncAPIDetails,
readSchemaFromFile,
getAppSyncAPIInfoFromProject,
} = require('../utils');
const { generateGraphQLDocuments } = require('@aws-amplify/graphql-docs-generator');
const { generateStatements: generateStatementsHelper } = require('@aws-amplify/graphql-generator');

Expand All @@ -16,9 +22,18 @@ async function generateStatements(context, forceDownloadSchema, maxDepth, withou
}
const config = loadConfig(context, withoutInit);
const projects = config.getProjects();
if (!projects.length && withoutInit) {
context.print.info(constants.ERROR_CODEGEN_NO_API_CONFIGURED);
return;
}
let apis = [];
if (!withoutInit) {
apis = getAppSyncAPIDetails(context);
} else {
const api = getAppSyncAPIInfoFromProject(context, projects[0]);
if (api) {
apis = [api];
}
}
let projectPath = process.cwd();
if (!withoutInit) {
Expand All @@ -30,26 +45,18 @@ async function generateStatements(context, forceDownloadSchema, maxDepth, withou
return;
}
}
if (!projects.length && withoutInit) {
context.print.info(constants.ERROR_CODEGEN_NO_API_CONFIGURED);
return;
}

for (const cfg of projects) {
const includeFiles = path.join(projectPath, cfg.includes[0]);
const opsGenDirectory = cfg.amplifyExtension.docsFilePath
? path.join(projectPath, cfg.amplifyExtension.docsFilePath)
: path.dirname(path.dirname(includeFiles));
const schemaPath = path.join(projectPath, cfg.schema);
let region;
let frontend;
if (!withoutInit) {
({ region } = cfg.amplifyExtension);
if (apis.length) {
const { region } = cfg.amplifyExtension;
await ensureIntrospectionSchema(context, schemaPath, apis[0], region, forceDownloadSchema);
frontend = getFrontEndHandler(context);
} else {
frontend = decoupleFrontend;
}
const frontend = withoutInit ? cfg.amplifyExtension.frontend : getFrontEndHandler(context);
const language = frontend === 'javascript' ? cfg.amplifyExtension.codeGenTarget : 'graphql';

const opsGenSpinner = new Ora(constants.INFO_MESSAGE_OPS_GEN);
Expand Down
22 changes: 18 additions & 4 deletions packages/amplify-codegen/src/commands/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const glob = require('glob-all');

const constants = require('../constants');
const { loadConfig } = require('../codegen-config');
const { ensureIntrospectionSchema, getFrontEndHandler, getAppSyncAPIDetails } = require('../utils');
const { ensureIntrospectionSchema, getFrontEndHandler, getAppSyncAPIDetails, getAppSyncAPIInfoFromProject } = require('../utils');
const { generateTypes: generateTypesHelper } = require('@aws-amplify/graphql-generator');
const { extractDocumentFromJavascript } = require('@aws-amplify/graphql-types-generator');

Expand All @@ -22,9 +22,18 @@ async function generateTypes(context, forceDownloadSchema, withoutInit = false,
if (frontend !== 'android') {
const config = loadConfig(context, withoutInit);
const projects = config.getProjects();
if (!projects.length && withoutInit) {
context.print.info(constants.ERROR_CODEGEN_NO_API_CONFIGURED);
return;
}
let apis = [];
if (!withoutInit) {
apis = getAppSyncAPIDetails(context);
} else {
const api = getAppSyncAPIInfoFromProject(context, projects[0]);
if (api) {
apis = [api];
}
}
if (!projects.length || !apis.length) {
if (!withoutInit) {
Expand Down Expand Up @@ -68,10 +77,15 @@ async function generateTypes(context, forceDownloadSchema, withoutInit = false,
.join('\n');

const schemaPath = path.join(projectPath, cfg.schema);
let region;
if (!withoutInit) {
({ region } = cfg.amplifyExtension);

const outputPath = path.join(projectPath, generatedFileName);
if (apis.length) {
const { region } = cfg.amplifyExtension;
await ensureIntrospectionSchema(context, schemaPath, apis[0], region, forceDownloadSchema);
} else {
if (!fs.existsSync(schemaPath)) {
throw new Error(`Cannot find GraphQL schema file: ${schemaPath}`);
}
}
const codeGenSpinner = new Ora(constants.INFO_MESSAGE_CODEGEN_GENERATE_STARTED);
codeGenSpinner.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ const generateIntrospectionSchema = require('./generateIntrospectionSchema');
const downloadIntrospectionSchemaWithProgress = require('./generateIntrospectionSchemaWithProgress');

async function ensureIntrospectionSchema(context, schemaPath, apiConfig, region, forceDownloadSchema) {
const meta = context.amplify.getProjectMeta();
let meta;
try {
meta = context.amplify.getProjectMeta();
} catch {}
const { id, name } = apiConfig;
const isTransformedAPI = Object.keys(meta.api || {}).includes(name) && meta.api[name].providerPlugin === 'awscloudformation';
const isTransformedAPI = meta && Object.keys(meta.api || {}).includes(name) && meta.api[name].providerPlugin === 'awscloudformation';
if (isTransformedAPI && getFrontendHandler(context) === 'android') {
generateIntrospectionSchema(context, name);
} else if (schemaPath.endsWith('.json')) {
Expand Down
15 changes: 15 additions & 0 deletions packages/amplify-codegen/src/utils/getAppSyncAPIInfoFromProject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const getAppSyncAPIInfo = require('./getAppSyncAPIInfo');

/* Get AppSync api info if api id and region are avialable.
* Otherwise return undefined.
*/
function getAppSyncAPIInfoFromProject(project, context) {
if (project.amplifyExtension.apiId && project.amplifyExtension.region) {
const {
amplifyExtension: { apiId, region },
} = project;
return getAppSyncAPIInfo(context, apiId, region);
}
return undefined;
}
module.exports = getAppSyncAPIInfoFromProject;
2 changes: 2 additions & 0 deletions packages/amplify-codegen/src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const downloadIntrospectionSchema = require('./downloadIntrospectionSchema');
const getSchemaDownloadLocation = require('./getSchemaDownloadLocation');
const getIncludePattern = require('./getIncludePattern');
const getAppSyncAPIInfo = require('./getAppSyncAPIInfo');
const getAppSyncAPIInfoFromProject = require('./getAppSyncAPIInfoFromProject');
const getProjectAwsRegion = require('./getProjectAWSRegion');
const getGraphQLDocPath = require('./getGraphQLDocPath');
const downloadIntrospectionSchemaWithProgress = require('./generateIntrospectionSchemaWithProgress');
Expand All @@ -24,6 +25,7 @@ module.exports = {
downloadIntrospectionSchemaWithProgress,
getIncludePattern,
getAppSyncAPIInfo,
getAppSyncAPIInfoFromProject,
getProjectAwsRegion,
getGraphQLDocPath,
isAppSyncApiPendingPush,
Expand Down
Loading