Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom scalars to GraphQL Codegen?

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

like image 745
Stretch0 Avatar asked Oct 16 '25 04:10

Stretch0


1 Answers

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
like image 79
Bergi Avatar answered Oct 17 '25 17:10

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!