问题
I need to call a mutation from a cron job running on the server. I found this SO post, but the accepted answer said there was no way to do it.
Then I found this on GitHub, from 2017:
graphql-server is an network wrapper for graphql core function. if you don't want to use it over network, you can just run it standalone:
import scheme from './scheme'; const query = `{ me { name } }`; const result = graphql(scheme, query); console.log(result);
function documentation can be found here
That looks pretty good! Is that the best practices approach in 2020?
回答1:
Yes, if you have access to the GraphQLSchema
object used by your GraphQL server, then the simplest approach is to just use the graphql function exported by the graphql
module. Note that you should await the returned Promise to access the result:
async function run () {
const { data, errors } = await graphql(
schema,
query,
rootValue,
context,
variables
)
}
However, you can also make requests to the server itself over the network -- if the server is on the same host, you'd just use localhost
or 127.0.0.1
. In that case, you can use axios
, request
or any other HTTP client library in a Node.js script. You can also just use curl
to make the request directly in a bash script or curl command.
回答2:
I just found out about this approach as well. It's possible to create an Apollo client directly on the server.
export const getApolloServerClient = () =>
new ApolloClient({
ssrMode: true,
cache: new InMemoryCache(),
link: new SchemaLink({ schema }),
});
来源:https://stackoverflow.com/questions/61989961/apollo-graphql-call-a-mutation-from-the-server