未加星标

Building a GraphQL Server with Node.js and Express

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

GraphQL enables us to build a server that a client can query in any way they want. I’m of course talking about content negotiation, the ability to ask the server exactly for the fields or resources they want, at any depth.

In a previous article Building your first GraphQL Server , I’ve covered what different artefacts and types that make out a GraphQL server. In this article we will focus more on how to build a service, powered by GraphQL that clients can consume. We will also introduce a playground environment called GraphiQL that gives us a UI in which we can test our queries out.


Building a GraphQL Server with Node.js and Express

A GraphQL Server consists of the following:

a schema , the schema defines our entities but also what we can query or call a mutation on resolvers , resolver functions talks to a 3rd party API or our database and ends up returning data back to our user Install dependencies

Let’s start off by installing our needed dependencies. We need the following:

express , to create our web server graphql , to install graphql, our core lib that enables us to leverage graphql express-graphql , this library enables us to bind together graphql and express express + graphql(only)

Let’s start off by only install graphql and express to understand what that gives us:

npm install express graphql

Thereafter let’s create an express HTTP server, like so:

// schema.mjs import { graphql, GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList } from “graphql”; let humanType = new GraphQLObjectType({ name: “Human”, fields: () => ({ id: { type: GraphQLString }, description: { type: GraphQLString }, name: { type: GraphQLString } }) }); import people from “./data/people”; let schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: “RootQueryType”, fields: { hello: { type: GraphQLString, resolve() { return “world”; } }, person: { type: humanType, resolve() { return people[0]; } }, people: { type: new GraphQLList(humanType), resolve() { return people; } } } }) }); export { graphql }; export default schema;

This is a pretty simple schema that declare hello , person and people as queryable keywords and it also creates humanType as a custom type.

Short comment on the file ending .mjs . What we are doing here is to leverage experimental support for ESM/EcmaScript modules. The way they are currently implemented in NodeJS forces us to have a file ending of .mjs .

Next up is the app itself that is just a basic express application looking like this:

// app.mjs import express from “express”; const app = express(); const port = 3000; import schema, { graphql } from “./schema”; app.get(“/”, (req, res) => { let query = `{ hello, person { name }, people { name, description } }`; graphql(schema, query).then(result => { res.json(result); }); }); app.listen(port, () => console.log(`Example app listening on port port!`));

Above we are declaring a default route by calling:

app.get("/", (req, res) => { });

Then we add the graphql part by invoking it with parameters schema and query , like so:

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

As we can see above invoking graphql means we get a promise back and on the then() callback we are able to see the result from our query. All together we can see how graphql and express can interact.

Lastly to run this we need to specify a start command in our package.json file that invokes the experimental support for ESM modules. It needs to look like so:

// excerpt from package.json “start”: “node ― experimental-modules app.mjs” adding express-graphql

We just showed how we can use express and graphql and create a REST api, but we can do this better by adding express-graphql , so let’s do that as our next thing:

npm install express-graphql

Let’s do something else first, for ourselves, namely use the buildSchema() method and set up a schema that way, like so:

var { buildSchema } = require(“graphql”); var schema = buildSchema(` type Product { name: String, id: Int }, type Query { hello: String, products: [Product] } );

Above we can see that we define the custom type Product and we also define our queries being hello and products .

We also need some resolver functions with that which we define next:

var root = { hello: () => { return "Hello world!"; }, products: () => { return getProducts(); } };

Lastly we are able to clean up our code a bit so our code for starting our server looks like this now:

var graphqlHTTP = require("express-graphql"); app.use( '/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true }) );

That’s it, we don’t actually need to define any routes but we leave that up to graphql. We can see that graphqlHTTP() is a function that we get from express-graphql

Now we have all the bits in place.

Graphiql

When we called our graphqlHTTP() function we provided it with a configuration object that had the following properties set:

schema , our GraphQL schema rootValue , our resolver functions graphiql , a boolean stating wether to use graphiql , we want that so we pass `true` here

Next step is to try out graphiql which we do by navigating to http://localhost:4000/graphql and voila, this is what you should be seeing:


Building a GraphQL Server with Node.js and Express

Ok great, a visual interface, now what?

Well now you can start creating Graphql queries. To know what to query for, have a look at what you defined in the schema.

We expect that we will be able to query for hello and products as we set those up in our schema. So let’s do that:


Building a GraphQL Server with Node.js and Express

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Building a GraphQL Server with Node.js and Express
本站链接:https://www.codesec.net/view/628206.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(66)