question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Async scalars with access to `context` and `info`?

See original GitHub issue

In our resolver map, we have two quite different things:

  1. Resolvers, which are functions called by graphql-js with useful objects like info or context, and they are usually async.
  2. Custom scalars, which are objects, don’t have access to info or context (or anything request-related) and their functions like serialize aren’t async.

I wonder if scalars could be more resolver-like?!

Concrete example

Our use case is price rounding. In our case, GraphQL server code doesn’t know how to round – it needs to ask a backend API for rounding rules – but it is GraphQL code’s responsibility to ensure that values are rounded.

Most prices in our schema are represented by a Money type that looks like this:

type Money {
  amount: MonetaryAmount! # custom scalar
  currencyCode: String!
}

We can then do something like this, which works well:

const resolvers = {
  Query: {
    Money: {
      amount: async (money, _, { dataSources: { backendApi } }) =>
        round(money.amount, money.currencyCode, backendApi),
    },
  }
};

async function round(amount, currency, backendApi) {
  const roundingInfo = await backendApi.getRoundingInfo(...);
  // etc.
}

Some parts of our schema, however, use the scalar directly, skipping the Money type. For example:

type GoogleEcommerceDataLayerActionField {
  id: String!
  revenue: MonetaryAmount
  tax: MonetaryAmount
}

I’d love to be able to write resolver-like code for it, like this:

// pseudocode!

const resolvers = {
  __customScalars: {
    MonetaryAmount: async (value, { config, dataSources: { backendApi } }) =>
      round(value, config.currencyCode, backendApi),
  },
};

Currently, we need to solve this on the specific field level, for example, if there’s a field like:

type GoogleEcommercePurchaseDataLayer {
  actionField: GoogleEcommerceDataLayerActionField
}

we can hook into actionField and process the rounding there. But it would be safer and easier if we could solve it at the type level.

What do you think? Has this been considered before? I didn’t find much but maybe my search skills have failed me.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:16 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
IvanGoncharovcommented, Jun 19, 2020

IF we ignore inputs for now, do you think the serialize’s signature could be changed to support such use case?

We use serialize for printing schemas with default values and also for sending default values inside introspection. So we need to also keep it request-independent.

When scalars are used as default values in SDL, there is no way this could ever be async, and there’s certainly no context object at that point.

Yes, it true for both parsing/printing SDL and sending/receiving introspection results.

When inputs are parsed from a query, the ‘parse’ functions could theoretically be async, and be given context as an argument. (Not sure if a good idea or not but it would probably work, technically.)

Theoretically yes, practically it would result in very strange API where a function doesn’t receive most of the parameters and can respond with a promise only in certain situations.

Moreover awaiting inside every serialize will kill your performance since every await (even if the promise is already resolved) goes through microtasks queue, what’s even worse is that by making more leaves return promises you forcing more of execution to be done in async mode. It will totally kill performance if you returning big arrays of such scalars, for context please see: https://github.com/graphql/graphql-js/issues/723#issuecomment-383346375 So what’s why we limiting async to only functions that absolutely need it like resolve and resolveType.

What you can do is to use wrappers for numbers that you want to wrap and address rounding it before or during serilization:

class NumberWithRounding {
  constructor(private value: Number) {}
  valueOf() { return this.value; }
  round(decimalPlaces) { return round(value, decimalPlaces); }
}

const MonetaryAmount = new GraphQLScalarType({
  serialize: (value) => new NumberWithRounding(value),
});

// ...
const roundingInfo = await context.backendApi.getRoundingInfo(...);
JSON.stringify(result, (_key, value) {
  if (value instanceof NumberWithRounding) {
    return value.round(roundingInfo.decimalPlaces);
  }
  return value;
})
0reactions
yaacovCRcommented, May 20, 2022

Note that the use case in the related ticket #3539 relates to customizing error message languages, with the parse/serialize functions the normal place where these errors and messages are generated.

The implementation within #3600 that allows access to context is meant for only scalar-specific work such as the above. For that reason, the functions remain synchronous, and access to info is not provided.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Asynchronous I/O (asyncio) - SQLAlchemy 1.4 Documentation
run_async() that allows an awaitable function to be invoked within the “synchronous” context of an event handler or other SQLAlchemy internal.
Read more >
Context - Async-graphql Book
Context. The main goal of Context is to acquire global data attached to Schema and also data related to the actual query being...
Read more >
Resolvers - Apollo GraphQL Docs
An object shared across all resolvers that are executing for a particular operation. Use this to share per-operation state, including authentication information ......
Read more >
Async SqlAlchemy with FastAPI: Getting single session for all ...
When two requests come in parallel, and when the first request awaits at some DB operation, it hands over the control to the...
Read more >
Asynchronous Context Managers in Python
An asynchronous context manager is a Python object that implements the __aenter__() and __aexit__() methods. Before we dive into the details of ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found