graphile / crystal

🔮 Graphile's Crystal Monorepo; home to Grafast, PostGraphile, pg-introspection, pg-sql2 and much more!
https://graphile.org/
Other
12.62k stars 571 forks source link

How to add metadata into top level extensions property in GQL response? #2220

Open achintha-weerasinghe opened 4 weeks ago

achintha-weerasinghe commented 4 weeks ago

Documentation lacks details of adding data into the top level extensions property in the GQL response. I'm looking for an example where some data is copied from the context to the extensions just before sending the response to the client. Your help is appreciated. Thanks!

benjie commented 3 weeks ago

Indeed; this is not documented - help adding it to the documentation would be appreciated!

Fortunately it is possible to do it with a plugin like this:

const AddToResponseExtensionsPropertyPlugin: GraphileConfig.Plugin = {
  name: "AddToResponseExtensionsPropertyPlugin",

  grafast: {
    middleware: {
      execute(next, event) {
        return next.callback((error, result) => {
          if (error) throw error;
          const context = (event.args.contextValue ?? {}) as Grafast.Context;
          if (!isAsyncIterable(result)) {
            if (!result.extensions) result.extensions = {};
            result.extensions.number = context.number;
          }
          return result;
        });
      },
    },
  },
};

I don't think this middleware system has any documentation yet actually.