Log result related details to a database just before sending response to client?

Hi all,
currently my project requirement is, when a client send a query request, I need to log fetched result related details to a database, like “userIp”, ““userId”, datetime” and data they requested.
see below example:
query {
universalData (
identifiers: [“Y27183121”,“G51502105”, “G37585109”, “686330101” ],
betweenDates: {
startDate:“2021-06-05”,
endDate:“2021-06-16”
}
) {
priceData {
MIC
ISIN
Currency
PriceDate
Open
High
Low
Close
CUSIP
PrimaryExchgCD
ExchgCD
TotalTrades
CloseType
}
}
}

Currently I m thinking it as make a array and pass to context so that all resolver can have access to it. This array will store details that I need to send to database via an external API call.

I m not sure what is the best place to do this. The array will be fully populated after all resolvers have been resolved. How and where can I have hold on this array after resolver has been resolved to make api call with it.

Hello! This sounds like a great use case for creating a custom Apollo Server plugin.

Plugins can hook into various events during the GraphQL operation lifecycle, and it sounds like with your use case, you might want to hook into the willSendResponse event, which fires after an operation has been fully resolved (or an error occurs):

const myPlugin = {
  async requestDidStart() {
    return {
      // Called whenever Apollo Server is about to respond
      async willSendResponse(requestContext) {
        // Write to database in here
        console.log(requestContext.context);
      }
    },
  };
};

Plugin methods like willSendResponse are passed the operation’s GraphQLRequestContext, which includes a lot of useful info about the operation. The context field of that object is the shared context from your resolvers, so that’ll include the array you’re adding to. You should be able to write request details to your database in this method.

Hope this helps!

1 Like

Hi @StephenBarlow Thanks for your reply. I followed your approach and I m able to see my array in requestContext.context. I m not sure if apollo allow to make a rest api call in willSendResponse function. What are the options able to make a call to an external REST API.

You can do whatever you’d like in willSendResponse but be sure to consider that if it’s a blocking request, you will block the response!