Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute a mutation or query locally at server side with Apollo Server

I would like to know if it is possible to execute a mutation or query locally at server side with Apollo Server.

Example:

1- Endpoint GET /createNew is reached

2- I run a mutation I defined like:

apolloserver.mutation(mutation_query).then((response)=>{res.status(200)})

3- A new entry is added to the database and a JSON string is returned to client

Does something like that exist? Is a apolloserver object available at runtime?

I'm using NodeJS + Express

like image 947
Victor Ferreira Avatar asked Oct 27 '25 15:10

Victor Ferreira


1 Answers

I got it working

First we start the objects:

import express from 'express';
import { graphql } from 'graphql';
const context = require('./context'); //this is the object to be passed to each resolver function
const schema = require('./schema'); //this is the object returned by makeExecutableSchema({typeDefs, resolvers})
const app = express();

Then, if we want, for example, to run a query on endpoint GET /execute

app.get('/execute', function(req, res){
    var query = `
        query myQueryTitle{
            queryName{
                _id,
                ...
            }
        }
    `;

    graphql(schema, query, null, context)
    .then((result) => {
        res.json(result.data.queryName);
    });
})

So anytime we want to run a query or a mutation, we call graphql passing schema, the requestString/query and the context object

And this may coexist with an instance of graphqlExpress

like image 142
Victor Ferreira Avatar answered Oct 29 '25 07:10

Victor Ferreira