Home > Back-end >  How can I share data between 2 resolver functions in Express GraphQL?
How can I share data between 2 resolver functions in Express GraphQL?

Time:10-07

I have 2 queries, and corresponding functions, but while writing the resolver, I'm not sure how to store the 1st func data, then reuse it in the second one. Note: I do not want to call the function again as it will be executing again and has an inline API call. I just want to use it like a session on the global state in express js. Here's the code:

const resolvers={
    getStudent:async({id})=>{
        const resp=await service(id)
        return resp;
    },
    
    const courseDetails:()=>{
        console.log(resp)// I want to access resp object from above func., But don't want to call getStudent again
    }
}

I tried context but didn't work.

CodePudding user response:

You can implement a simple in-memory store. By storing the Promise and returning it you won't need to worry about multiple requests to the same resources.

const got = require('got');
const assert = require('assert');

function studentServiceFactory(options = {}) {
    const TTL = options.ttl || 60 * 60 * 5; // default 5 min ttl
    const BASE_API = "https://swapi.dev/api";
    const store = {};

    return {
        get: ({ id }) => {
            if(!store[id] || store[id].timestamp   TTL < Date.now()) {
                // store the promise
                store[id] = {
                    promise: got(`${BASE_API}/people/${id}`),
                    timestamp: Date.now(),
                };
                console.log(`${BASE_API}/people/${id}`);
            }
            return store[id].promise;
        }
    }
}

const studentService = studentServiceFactory({ ttl: 1000});
const resolvers = {
    studentService: studentService,
};


// test program
(async () => {
    const request1 = await resolvers.studentService.get({ id: 1 });
    const request2 = await resolvers.studentService.get({ id: 1 });
    // Both calls will return the same promise.

    assert.equal(request1, request2);

    // wait for resources to get stale 
    setTimeout(async() => {
        const request3 = await resolvers.studentService.get({ id: 1 });
        assert.notEqual(request1, request3);
    }, 3000);

})();

CodePudding user response:

Two requests are independent of each other. The only way to share data between two requests is to persist the data somewhere. It can be a file, database, etc. In your case, you can simply call the service function again in the other resolver.

  • Related