Unlocking the request object within a GraphQL resolver with Apollo-Server-Express

My express server is standard and I'm using GraphQL with it

const server = express();

server.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));

I am wondering how to access the request object within a resolver. Specifically, I need to verify the JWT in certain queries.

Below is the schema that has been imported:

const typeDefs = `
    type User {
        id: String,
        name: String,
        role: Int
    }
    type Query {
        user(id: String): User,
        users: [User]
    }
`;

const resolvers = {
    Query: {
        user: (_, args, context, info) => users.find(u => u.id === args.id),
        users: (_, args, context, info) => users
    }
}

module.exports = makeExecutableSchema({typeDefs, resolvers});

Answer №1

To access the request object, it is recommended to use the context. To customize the options in your graphqlExpress middleware and define your context, you can do the following:

server.use('/graphql', bodyParser.json(), graphqlExpress(req => ({
  schema,
  context: { user: req.user }
}))

It is worth noting that express-graphql defaults to using the request as the context if not specified in the options -- Apollo's middleware may function in a similar manner but this is not explicitly stated in the documentation.

Subsequently, the context can be accessed as the third parameter within your resolver function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatically redirect users on page refresh using jQuery

I am attempting to use jQuery to detect when the user refreshes the page in order to redirect, but I can't seem to get it working. Can someone help me figure out what is wrong with this code? <?php include 'instagram.php'; ?> <! ...

Adjust the loading bar component in Material UI to allow for customizable color changes

I am currently learning how to use material ui. My goal is to customize the loading bar's CSS. I checked the documentation and utilized colorPrimary classes. However, the changes are not appearing as expected. Could you please guide me on how to resol ...

Issue with using the bootstrap template plugin for cube portfolio

I have integrated cubeportfolio.js into a bootstrap template, but I am encountering an issue with the custom .js code included in the template that is causing an error in the console. You can view the template I am using here, and it appears to be functio ...

Issue encountered with search.run().getRange function when accessing a stored search in suitescript 2.0

I am facing an issue with my saved search in the beforeLoad userevent script. After adding a filter and running the search, Netsuite throws an UNEXPECTED_ERROR. Any ideas on what might be causing this error? var poRec = context.newRecord; var countIt ...

Tips for addressing the Stale Element Reference Exception when locating an element in JMeter

Trying to locate an element with a structure similar to the following: <div> <div> <div> <ul> <object id = "obj" #document (link here) <html> <head> </head> ...

Shuffle math calculations involving subtraction by a percentage using node.js or JavaScript

Hello there! If you want to subtract, say 35%, from a number, you can use methods like this: var valueInString = "2383"; var num = parseFloat(valueInString); var val = num - (num * .35); console.log(val); But have you ever wondered how you could randomiz ...

The onSubmit event handler seems to be malfunctioning within a Reactjs form

I recently started using React and encountered an issue with my form: class CustomForm extends React.Component { handleFormSubmit = (e) => { e.preventDefault(); const title = e.target.elements.title.value; const content = e ...

Is it possible to independently verify the results of promises within a $.when(...) function without regard to the overall outcome?

Take a look at this example: $.when(a1, a2, a3, a4, .....) .done(function (){alert('done')}) .fail(function (){alert('fail')}); If all promises from a1 to ax were successful, I can manage and handle all the data within t ...

The error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

What methods are recommended for expanding the size of a select/dropdown menu?

Managing a long list of values can be challenging, especially when it continues to grow. Consider the following example: <select> <option value="1">1, some test</option> <option value="2">2, some text</option> <optio ...

Implementing Etags in Express 4.x

I'm a bit unsure about how to utilize Etag in Express 4. As far as I know, when you set it up like this: app.use(express.static(path.join(__dirname, 'public'), { etag: true, maxAge:60000 })); it indicates that the browser will cach ...

Consolidate all data connected to the specified key from a JSON dataset

Looking at the json string presented below [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}] The expected outcome is: [{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}] Is there ...

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

What is the best way to transfer the content from a tinyMCE textarea editor to an inner controller using Symfony3 and Ajax

I have two small rich text editors identified as #homepage and #thankyoupage. My goal is to submit the content of these TinyMCE text areas to a Symfony controller. Below is my front-end implementation: https://i.stack.imgur.com/TE1Ys.jpg Currently, I am ...

Update the division by clicking the button with a randomly generated JavaScript string element

Trying to solve a unique problem here as none of the proposed solutions on similar questions have worked for me. Apologies if I'm missing something, I'm new at this. The issue is with loading an empty div on my page using javascript and strings ...

Ways to Achieve the Following with JavaScript, Cascading Style Sheets, and Hypertext

Can someone help me convert this image into HTML/CSS code? I'm completely lost on how to do this and don't even know where to start searching for answers. Any assistance would be greatly appreciated. Thank you in advance. ...

including a content tag into an input field within a template

I'm experimenting with the new html5 template tag to create a versatile form that can be used in various situations without relying heavily on javascript. Check out this fiddle to see what I have so far http://jsfiddle.net/684uH/ My objective is to ...

javascript loop exhibiting unpredictable behavior when making ajax requests

window.addEventListener('load',function(){ var last=0; var sub=document.getElementById("sub"); var msg=document.getElementById('msg'); var msg_bx=document.getElementById("msg_bx"); var re=new XMLHttpRequest(); re.open("GET","handler ...

React Header Component Experiencing Initial Scroll Jitters

Issue with Header Component in React Next.js Application Encountering a peculiar problem with the header component on my React-based next.js web application. When the page first loads and I begin scrolling, there is a noticeable jittery behavior before th ...