1

I have a custom scalar in my GraphQL schema and I want my Codegen to generate the correct type fo me.

My schema looks like this:

scalar Decimal

type Item {
  price: Decimal!
}

and I have added a custom resolver for this scalar which uses [Decimal.js][1].

When I generate my Typescript types from this schema, I want it to recognise price as a Decimal type and have the properties that Decimal.js provides.

My codegen config looks like this:

schema: "./src/typeDefs/index.ts"
generates:
  ./src/types.d.ts:
    config:
      scalars:
        Decimal: Decimal
    plugins:
      - typescript
      - typescript-resolvers

Whilst this generates Decimal types, it doesn't recognise it as a type of Decimal.js so it doesn't have any methods that the library exposes.

It generates the following type:

export type Scalars = {
  ID: string;
  String: string;
  Boolean: boolean;
  Int: number;
  Float: number;
  Decimal: Decimal; // doesn't have any Decimal.js props
};

How can I tell codegen to use Decimal.js to generate the correct type for Decimal? [1]: https://www.npmjs.com/package/decimal.js

Stretch0
  • 8,362
  • 13
  • 71
  • 133
  • Possible duplicate of https://stackoverflow.com/questions/71165178/adding-a-custom-type-to-codegen-yml? – Bergi Dec 26 '22 at 00:50

2 Answers2

2

It's not properly documented for the typescript plugin, but mentioned on the blog:

  • You can import your types from a node module package (User: models-lib#UserType).
  • You can also map to built-in language types (DateType: Date)
  • Aliasing the imports is also possible (User: ./models#User as MyCustomUserType)

This does not work only for mappers but also for scalars. So you're looking for

schema: "./src/typeDefs/index.ts"
generates:
  ./src/types.d.ts:
    config:
      scalars:
        Decimal: decimal.js#Decimal
#       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    plugins:
      - typescript
      - typescript-resolvers
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

You have to add the import to the graphql.ts file by adding an add in the codegen.yaml:

schema: "./src/typeDefs/index.ts"
generates:
  ./src/types.d.ts:
    config:
      scalars:
        Decimal: Decimal
    plugins:
      - typescript
      - typescript-resolvers
      - add:
        content: "import {Decimal} from 'Decimal.js';"