Skip to content

Commit be06165

Browse files
modernize js code samples (#2018)
1 parent 4d017fd commit be06165

15 files changed

+357
-295
lines changed

src/pages/graphql-js/authentication-and-express-middleware.mdx

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,41 +10,41 @@ To use middleware with a GraphQL resolver, just use the middleware like you woul
1010
For example, let's say we wanted our server to log the IP address of every request, and we also want to write an API that returns the IP address of the caller. We can do the former with middleware, and the latter by accessing the `request` object in a resolver. Here's server code that implements this:
1111

1212
```js
13-
var express = require("express")
14-
var { createHandler } = require("graphql-http/lib/use/express")
15-
var { buildSchema } = require("graphql")
13+
import express from "express";
14+
import { createHandler } from "graphql-http/lib/use/express";
15+
import { buildSchema } from "graphql";
1616

17-
var schema = buildSchema(`
17+
const schema = buildSchema(`
1818
type Query {
1919
ip: String
2020
}
21-
`)
21+
`);
2222

2323
function loggingMiddleware(req, res, next) {
24-
console.log("ip:", req.ip)
25-
next()
24+
console.log("ip:", req.ip);
25+
next();
2626
}
2727

28-
var root = {
28+
const root = {
2929
ip(args, context) {
30-
return context.ip
30+
return context.ip;
3131
},
32-
}
32+
};
3333

34-
var app = express()
35-
app.use(loggingMiddleware)
34+
const app = express();
35+
app.use(loggingMiddleware);
3636
app.all(
3737
"/graphql",
3838
createHandler({
39-
schema: schema,
39+
schema,
4040
rootValue: root,
41-
context: req => ({
41+
context: (req) => ({
4242
ip: req.raw.ip,
4343
}),
4444
})
45-
)
46-
app.listen(4000)
47-
console.log("Running a GraphQL API server at localhost:4000/graphql")
45+
);
46+
app.listen(4000);
47+
console.log("Running a GraphQL API server at localhost:4000/graphql");
4848
```
4949

5050
In a REST API, authentication is often handled with a header, that contains an auth token which proves what user is making this request. Express middleware processes these headers and puts authentication data on the Express `request` object. Some middleware modules that handle authentication like this are [Passport](http://passportjs.org/), [express-jwt](https://github.com/auth0/express-jwt), and [express-session](https://github.com/expressjs/session). Each of these modules works with `graphql-http`.

src/pages/graphql-js/basic-types.mdx

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,42 +13,42 @@ To use a list type, surround the type in square brackets, so `[Int]` is a list o
1313
Each of these types maps straightforwardly to JavaScript, so you can just return plain old JavaScript objects in APIs that return these types. Here's an example that shows how to use some of these basic types:
1414

1515
```js
16-
var express = require("express")
17-
var { createHandler } = require("graphql-http/lib/use/express")
18-
var { buildSchema } = require("graphql")
16+
import express from "express";
17+
import { createHandler } from "graphql-http/lib/use/express";
18+
import { buildSchema } from "graphql";
1919

2020
// Construct a schema, using GraphQL schema language
21-
var schema = buildSchema(`
21+
const schema = buildSchema(`
2222
type Query {
2323
quoteOfTheDay: String
2424
random: Float!
2525
rollThreeDice: [Int]
2626
}
27-
`)
27+
`);
2828

2929
// The root provides a resolver function for each API endpoint
30-
var root = {
30+
const root = {
3131
quoteOfTheDay() {
32-
return Math.random() < 0.5 ? "Take it easy" : "Salvation lies within"
32+
return Math.random() < 0.5 ? "Take it easy" : "Salvation lies within";
3333
},
3434
random() {
35-
return Math.random()
35+
return Math.random();
3636
},
3737
rollThreeDice() {
38-
return [1, 2, 3].map(_ => 1 + Math.floor(Math.random() * 6))
38+
return [1, 2, 3].map(() => 1 + Math.floor(Math.random() * 6));
3939
},
40-
}
40+
};
4141

42-
var app = express()
42+
const app = express();
4343
app.all(
4444
"/graphql",
4545
createHandler({
46-
schema: schema,
46+
schema,
4747
rootValue: root,
4848
})
49-
)
50-
app.listen(4000)
51-
console.log("Running a GraphQL API server at localhost:4000/graphql")
49+
);
50+
app.listen(4000);
51+
console.log("Running a GraphQL API server at localhost:4000/graphql");
5252
```
5353

5454
If you run this code with `node server.js` and browse to http://localhost:4000/graphql you can try out these APIs.

src/pages/graphql-js/constructing-types.mdx

Lines changed: 38 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ When you are using the `GraphQLSchema` constructor to create a schema, instead o
99
For example, let's say we are building a simple API that lets you fetch user data for a few hardcoded users based on an id. Using `buildSchema` we could write a server with:
1010

1111
```js
12-
var express = require("express")
13-
var { createHandler } = require("graphql-http/lib/use/express")
14-
var { buildSchema } = require("graphql")
12+
import express from "express";
13+
import { createHandler } from "graphql-http/lib/use/express";
14+
import { buildSchema } from "graphql";
1515

16-
var schema = buildSchema(`
16+
const schema = buildSchema(`
1717
type User {
1818
id: String
1919
name: String
@@ -22,10 +22,10 @@ var schema = buildSchema(`
2222
type Query {
2323
user(id: String): User
2424
}
25-
`)
25+
`);
2626

2727
// Maps id to User object
28-
var fakeDatabase = {
28+
const fakeDatabase = {
2929
a: {
3030
id: "a",
3131
name: "alice",
@@ -34,35 +34,39 @@ var fakeDatabase = {
3434
id: "b",
3535
name: "bob",
3636
},
37-
}
37+
};
3838

39-
var root = {
39+
const root = {
4040
user({ id }) {
41-
return fakeDatabase[id]
41+
return fakeDatabase[id];
4242
},
43-
}
43+
};
4444

45-
var app = express()
45+
const app = express();
4646
app.all(
4747
"/graphql",
4848
createHandler({
49-
schema: schema,
49+
schema,
5050
rootValue: root,
5151
})
52-
)
53-
app.listen(4000)
54-
console.log("Running a GraphQL API server at localhost:4000/graphql")
52+
);
53+
app.listen(4000);
54+
console.log("Running a GraphQL API server at localhost:4000/graphql");
5555
```
5656

5757
We can implement this same API without using GraphQL schema language:
5858

5959
```js
60-
var express = require("express")
61-
var { createHandler } = require("graphql-http/lib/use/express")
62-
var graphql = require("graphql")
60+
import express from "express";
61+
import { createHandler } from "graphql-http/lib/use/express";
62+
import {
63+
GraphQLObjectType,
64+
GraphQLString,
65+
GraphQLSchema,
66+
} from "graphql";
6367

6468
// Maps id to User object
65-
var fakeDatabase = {
69+
const fakeDatabase = {
6670
a: {
6771
id: "a",
6872
name: "alice",
@@ -71,45 +75,45 @@ var fakeDatabase = {
7175
id: "b",
7276
name: "bob",
7377
},
74-
}
78+
};
7579

7680
// Define the User type
77-
var userType = new graphql.GraphQLObjectType({
81+
const userType = new GraphQLObjectType({
7882
name: "User",
7983
fields: {
80-
id: { type: graphql.GraphQLString },
81-
name: { type: graphql.GraphQLString },
84+
id: { type: GraphQLString },
85+
name: { type: GraphQLString },
8286
},
83-
})
87+
});
8488

8589
// Define the Query type
86-
var queryType = new graphql.GraphQLObjectType({
90+
const queryType = new GraphQLObjectType({
8791
name: "Query",
8892
fields: {
8993
user: {
9094
type: userType,
9195
// `args` describes the arguments that the `user` query accepts
9296
args: {
93-
id: { type: graphql.GraphQLString },
97+
id: { type: GraphQLString },
9498
},
9599
resolve: (_, { id }) => {
96-
return fakeDatabase[id]
100+
return fakeDatabase[id];
97101
},
98102
},
99103
},
100-
})
104+
});
101105

102-
var schema = new graphql.GraphQLSchema({ query: queryType })
106+
const schema = new GraphQLSchema({ query: queryType });
103107

104-
var app = express()
108+
const app = express();
105109
app.all(
106110
"/graphql",
107111
createHandler({
108-
schema: schema,
112+
schema,
109113
})
110-
)
111-
app.listen(4000)
112-
console.log("Running a GraphQL API server at localhost:4000/graphql")
114+
);
115+
app.listen(4000);
116+
console.log("Running a GraphQL API server at localhost:4000/graphql");
113117
```
114118

115119
When we use this method of creating the API, the root level resolvers are implemented on the `Query` and `Mutation` types rather than on a `root` object.

src/pages/graphql-js/graphql-clients.mdx

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,13 @@ fetch("/graphql", {
3232
},
3333
body: JSON.stringify({ query: "{ hello }" }),
3434
})
35-
.then(r => r.json())
36-
.then(data => console.log("data returned:", data))
35+
.then(response => response.json())
36+
.then(data => {
37+
console.log("Data returned:", data);
38+
})
39+
.catch(error => {
40+
console.error("Request failed:", error);
41+
});
3742
```
3843

3944
You should see the data returned, logged in the console:
@@ -55,11 +60,14 @@ type Query {
5560
You could access this from JavaScript with the code:
5661

5762
```js
58-
var dice = 3
59-
var sides = 6
60-
var query = /* GraphQL */`query RollDice($dice: Int!, $sides: Int) {
61-
rollDice(numDice: $dice, numSides: $sides)
62-
}`
63+
const dice = 3;
64+
const sides = 6;
65+
66+
const query = /* GraphQL */ `
67+
query RollDice($dice: Int!, $sides: Int) {
68+
rollDice(numDice: $dice, numSides: $sides)
69+
}
70+
`;
6371

6472
fetch("/graphql", {
6573
method: "POST",
@@ -72,8 +80,13 @@ fetch("/graphql", {
7280
variables: { dice, sides },
7381
}),
7482
})
75-
.then(r => r.json())
76-
.then(data => console.log("data returned:", data))
83+
.then(response => response.json())
84+
.then(data => {
85+
console.log("Data returned:", data);
86+
})
87+
.catch(error => {
88+
console.error("Request failed:", error);
89+
});
7790
```
7891

7992
Using this syntax for variables is a good idea because it automatically prevents bugs due to escaping, and it makes it easier to monitor your server.

0 commit comments

Comments
 (0)