Skip to content

Commit

Permalink
codegen: Remove default values for primitive schema fields
Browse files Browse the repository at this point in the history
In the AssemblyScript update a new feature was added to the CLI.

Schemas with types such as:

```graphql
type Total @entity {
  id: ID!
  amount: BigInt
}
```

Started to have their setters called on the constructor with the default
value for the type, eg:

```typescript
export class Total extends Entity {
  constructor(id: string) {
    super();
    this.set("id", Value.fromString(id));

    this.set("amount", Value.fromBigInt(BigInt.zero()));
  }
  // ...
}
```

The problem is that these new set calls were being called with
primitives as well, that is a bug.

This commit fixes the issue by checking if the field is primitive to
avoid generating the wrong call.
  • Loading branch information
evaporei committed Dec 3, 2021
1 parent 77546f3 commit 8318074
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/codegen/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,17 +80,24 @@ module.exports = class SchemaCodeGenerator {
.map(field => {
const name = field.getIn(['name', 'value'])
const type = this._typeFromGraphQl(field.get('type'))

const isNullable = type instanceof tsCodegen.NullableType
const isPrimitive = type.isPrimitive && type.isPrimitive()

const directives = field.get('directives')
const isDerivedFrom = directives.some(directive => directive.getIn(['name', 'value']) === 'derivedFrom')

return { name, type, isNullable, isDerivedFrom }
return { name, type, isNullable, isPrimitive, isDerivedFrom }
})
// We only call the setter with the default value in the constructor for fields that are:
// - Not primitive (such as Int/i32)
// - Not nullable, so that AS doesn't break when subgraph developers try to access them before a `set`
// - Not tagged as `derivedFrom`, because they only exist in query time
.filter(({ isNullable, isDerivedFrom }) => !isNullable && !isDerivedFrom)
.filter(({
isNullable,
isPrimitive,
isDerivedFrom,
}) => !(isNullable || isPrimitive || isDerivedFrom))
.map(({ name, type, isNullable }) => {
const fieldTypeString = isNullable ? type.inner.toString() : type.toString()

Expand Down

0 comments on commit 8318074

Please sign in to comment.