Skip to content

Commit

Permalink
fix(api): handle error on generate ts data schema when no tables with…
Browse files Browse the repository at this point in the history
… primary key
  • Loading branch information
sundersc committed Apr 20, 2024
1 parent 72ca6ba commit 874a520
Show file tree
Hide file tree
Showing 7 changed files with 153 additions and 3 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { compoundExpression, list, methodCall, nul, obj, printBlock, qref, ref, set, str, Expression } from 'graphql-mapping-template';
import { TransformerContextProvider } from '@aws-amplify/graphql-transformer-interfaces';
import { FieldDefinitionNode, ObjectTypeDefinitionNode } from 'graphql';
import { constructArrayFieldsStatement, constructNonScalarFieldsStatement } from '@aws-amplify/graphql-model-transformer';
import { ConfiguredAuthProviders, RoleDefinition } from '../../../utils';
import { constructAuthorizedInputStatement, emptyPayload, generateAuthRulesFromRoles, validateAuthResult } from './common';

Expand Down Expand Up @@ -64,6 +65,8 @@ export const generateAuthRequestExpression = (ctx: TransformerContextProvider, d
set(ref('lambdaInput.operationName'), str(operationName)),
set(ref('lambdaInput.args.metadata'), obj({})),
set(ref('lambdaInput.args.metadata.keys'), list([])),
constructNonScalarFieldsStatement(def.name.value, ctx),
constructArrayFieldsStatement(def.name.value, ctx),
constructFieldMappingInput(),
qref(
methodCall(ref('lambdaInput.args.metadata.keys.addAll'), methodCall(ref('util.defaultIfNull'), ref('ctx.stash.keys'), list([]))),
Expand Down
6 changes: 6 additions & 0 deletions packages/amplify-graphql-model-transformer/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ export const addDirectivesToOperation: (ctx: TransformerTransformSchemaStepConte
// @public (undocumented)
export const addModelConditionInputs: (ctx: TransformerTransformSchemaStepContextProvider) => void;

// @public (undocumented)
export const constructArrayFieldsStatement: (tableName: string, ctx: TransformerContextProvider) => Expression;

// @public (undocumented)
export const constructNonScalarFieldsStatement: (tableName: string, ctx: TransformerContextProvider) => Expression;

// @public (undocumented)
export const createEnumModelFilters: (ctx: TransformerTransformSchemaStepContextProvider, type: ObjectTypeDefinitionNode) => InputObjectTypeDefinitionNode[];

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './generators';
export * from './common';
export { constructArrayFieldsStatement, constructNonScalarFieldsStatement } from './rds';
export { generateApplyDefaultsToInputTemplate } from './dynamodb';
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,30 @@ export const schema = a.schema({
"
`;

exports[`Type name conversions generate typescript data schema should skip processing tables without primary key 1`] = `
"/* eslint-disable */
/* THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. */
import { a } from \\"@aws-amplify/data-schema\\";
import { configure } from \\"@aws-amplify/data-schema/internals\\";
import { secret } from \\"@aws-amplify/backend\\";
export const schema = configure({
database: {
identifier: \\"ID1234567890\\",
engine: \\"mysql\\",
connectionUri: secret(\\"CONN_STR\\")
}
}).schema({
\\"User\\": a.model({
id: a.string().required(),
name: a.string()
}).identifier([
\\"id\\"
])
});
"
`;

exports[`Type name conversions generates enum imports correctly 1`] = `
"/* eslint-disable */
/* THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,48 @@ describe('Type name conversions', () => {
const graphqlSchema = generateTypescriptDataSchema(dbschema, config);
expect(graphqlSchema).toMatchSnapshot();
});

it('generate typescript data schema should skip processing tables without primary key', () => {
const dbschema = new Schema(new Engine('MySQL'));
let model = new Model('User');
model.addField(new Field('id', { kind: 'NonNull', type: { kind: 'Scalar', name: 'String' } }));
model.addField(new Field('name', { kind: 'Scalar', name: 'String' }));
model.setPrimaryKey(['id']);
dbschema.addModel(model);

model = new Model('Profile');
model.addField(new Field('id', { kind: 'NonNull', type: { kind: 'Scalar', name: 'String' } }));
model.addField(new Field('details', { kind: 'Scalar', name: 'String' }));
dbschema.addModel(model);

const config: DataSourceConfig = {
identifier: 'ID1234567890',
secretName: 'CONN_STR',
};

const graphqlSchema = generateTypescriptDataSchema(dbschema, config);
expect(graphqlSchema).toMatchSnapshot();
});

it('generate typescript data schema throw error if none of the tables have primary key', () => {
const dbschema = new Schema(new Engine('MySQL'));
let model = new Model('User');
model.addField(new Field('id', { kind: 'NonNull', type: { kind: 'Scalar', name: 'String' } }));
model.addField(new Field('name', { kind: 'Scalar', name: 'String' }));
dbschema.addModel(model);

model = new Model('Profile');
model.addField(new Field('id', { kind: 'NonNull', type: { kind: 'Scalar', name: 'String' } }));
model.addField(new Field('details', { kind: 'Scalar', name: 'String' }));
dbschema.addModel(model);

const config: DataSourceConfig = {
identifier: 'ID1234567890',
secretName: 'CONN_STR',
};

expect(() => generateTypescriptDataSchema(dbschema, config)).toThrowError(
'No valid tables found. Make sure at least one table has a primary key.',
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,17 @@ export type DataSourceConfig = {
* @returns Typescript data schema in TS Node format
*/
export const createSchema = (schema: Schema, config?: DataSourceConfig): ts.Node => {
const models = schema.getModels().map((model) => {
return createModel(model);
});
const modelsWithPrimaryKeyCount = schema.getModels().filter((model) => model.getPrimaryKey()).length;
if (modelsWithPrimaryKeyCount === 0) {
throw new Error('No valid tables found. Make sure at least one table has a primary key.');
}

const models = schema
.getModels()
.filter((model) => model.getPrimaryKey())
.map((model) => {
return createModel(model);
});
const tsSchema = ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
createConfigureExpression(schema, config),
Expand Down

0 comments on commit 874a520

Please sign in to comment.