Skip to content

Commit bfe5eba

Browse files
danielreardenUrigo
authored andcommitted
Add GraphQL Helix example
1 parent 97fdede commit bfe5eba

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

src/content/code/language-support/javascript/server/graphql-helix.md

+75
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,79 @@ github: contrawork/graphql-helix
66
npm: "graphql-helix"
77
---
88

9+
To run a hello world server with GraphQL Helix:
910

11+
```bash
12+
npm install graphql graphql-helix express
13+
```
14+
15+
Then run `node server.js` with this code in `server.js`:
16+
17+
```js
18+
const express = require('express')
19+
const {
20+
GraphQLObjectType,
21+
GraphQLSchema,
22+
GraphQLString
23+
} = require('graphql');
24+
const {
25+
getGraphQLParameters,
26+
processRequest,
27+
renderGraphiQL,
28+
shouldRenderGraphiQL
29+
} = require('graphql-helix');
30+
31+
const schema = new GraphQLSchema({
32+
query: new GraphQLObjectType({
33+
name: 'Query',
34+
fields: {
35+
hello: {
36+
type: GraphQLString,
37+
resolve: () => 'Hello world!',
38+
},
39+
},
40+
}),
41+
});
42+
43+
const app = express();
44+
45+
app.use(express.json());
46+
47+
app.use('/graphql', async (req, res) => {
48+
const request = {
49+
body: req.body,
50+
headers: req.headers,
51+
method: req.method,
52+
query: req.query,
53+
};
54+
55+
if (shouldRenderGraphiQL(request)) {
56+
res.send(renderGraphiQL());
57+
} else {
58+
const { operationName, query, variables } = getGraphQLParameters(request);
59+
60+
const result = await processRequest({
61+
operationName,
62+
query,
63+
variables,
64+
request,
65+
schema,
66+
});
67+
68+
if (result.type === 'RESPONSE') {
69+
result.headers.forEach(({ name, value }) => res.setHeader(name, value));
70+
res.status(result.status);
71+
res.json(result.payload);
72+
} else {
73+
// graphql-helix also supports subscriptions and incremental delivery (i.e. @defer and @stream directives)
74+
// out of the box. See the repo for more complete examples that also implement those features.
75+
}
76+
}
77+
});
78+
79+
app.listen(4000, () =>
80+
console.log('Now browse to http://localhost:4000/graphql');
81+
)
82+
```
83+
84+
This example uses Express, but GraphQL Helix is framework- and runtime-agnostic -- it can run in Node, Deno and the browser. GraphQL Helix provides you with a handful of utility functions to build your own HTTP server but leaves the ultimate implementation details up to you.

0 commit comments

Comments
 (0)