amplify-codegen icon indicating copy to clipboard operation
amplify-codegen copied to clipboard

When creating a type with a sort key on the id field, codegen is making id required

Open focomoso opened this issue 2 years ago • 4 comments

Amplify CLI Version

12.1.1

Question

When creating a type in schema.graphql like this

type NodeModel
  @model
  @auth(rules: [{ allow: private}])
{
  id: ID! @primaryKey
  ...
}

codegen creates a type like this:

type LazyNodeModel = {
  readonly [__modelMeta__]: {
    identifier: OptionallyManagedIdentifier<NodeModel, 'id'>;
  };
  readonly id: string;
  ...
}

Which allows me to do:

const node = new NodeModel({
  // id not required
  // other fields...
})

The ID is not required.

But if I add a sort key to the primary key like this:

type NodeModel
  @model
  @auth(rules: [{ allow: private}])
{
 id: ID! @primaryKey(sortKeyFields: ["someOtherID"])
 ...
}

The generated type is:

type LazyNodeModel = {
  readonly [__modelMeta__]: {
    identifier: CompositeIdentifier<NodeModel, ['id', 'someOtherID']>;
  };
  readonly id: string;
  ...
}

And when I try to do:

const node = new NodeModel({
  id: 'some-value', // typescript complains if I don't add this
  // other fields...
});

It's requiring that I specify the ID myself.

Is this a bug or am I misusing the @primarayKey and sortKeyFields directives?

focomoso avatar Jul 24 '23 10:07 focomoso

Hey, 👋 thanks for raising this! I'm going to transfer this over to our codegen repository for better assistance 🙂

ykethan avatar Jul 24 '23 14:07 ykethan

This appears to be a bug. id should be auto-populated in the @primaryKey on id field with sort key case.

https://docs.amplify.aws/lib/datastore/advanced-workflows/q/platform/js/#determine-when-the-primary-key-field-is-auto-populated-upon-record-creation

dpilch avatar Aug 01 '23 19:08 dpilch

This is a breaking change for us, had to roll back to older versions which worked fine.

gregorsiwinski avatar Aug 21 '23 01:08 gregorsiwinski

Dependent on https://github.com/aws-amplify/amplify-js/pull/11707

dpilch avatar Sep 05 '23 14:09 dpilch