Skip to content

chore: modernize js code samples in docs #2018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions src/pages/graphql-js/authentication-and-express-middleware.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,41 +10,41 @@ To use middleware with a GraphQL resolver, just use the middleware like you woul
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:

```js
var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
import express from "express";
import { createHandler } from "graphql-http/lib/use/express";
import { buildSchema } from "graphql";

var schema = buildSchema(`
const schema = buildSchema(`
type Query {
ip: String
}
`)
`);

function loggingMiddleware(req, res, next) {
console.log("ip:", req.ip)
next()
console.log("ip:", req.ip);
next();
}

var root = {
const root = {
ip(args, context) {
return context.ip
return context.ip;
},
}
};

var app = express()
app.use(loggingMiddleware)
const app = express();
app.use(loggingMiddleware);
app.all(
"/graphql",
createHandler({
schema: schema,
schema,
rootValue: root,
context: req => ({
context: (req) => ({
ip: req.raw.ip,
}),
})
)
app.listen(4000)
console.log("Running a GraphQL API server at localhost:4000/graphql")
);
app.listen(4000);
console.log("Running a GraphQL API server at localhost:4000/graphql");
```

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`.
Expand Down
30 changes: 15 additions & 15 deletions src/pages/graphql-js/basic-types.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,42 +13,42 @@ To use a list type, surround the type in square brackets, so `[Int]` is a list o
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:

```js
var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
import express from "express";
import { createHandler } from "graphql-http/lib/use/express";
import { buildSchema } from "graphql";

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
const schema = buildSchema(`
type Query {
quoteOfTheDay: String
random: Float!
rollThreeDice: [Int]
}
`)
`);

// The root provides a resolver function for each API endpoint
var root = {
const root = {
quoteOfTheDay() {
return Math.random() < 0.5 ? "Take it easy" : "Salvation lies within"
return Math.random() < 0.5 ? "Take it easy" : "Salvation lies within";
},
random() {
return Math.random()
return Math.random();
},
rollThreeDice() {
return [1, 2, 3].map(_ => 1 + Math.floor(Math.random() * 6))
return [1, 2, 3].map(() => 1 + Math.floor(Math.random() * 6));
},
}
};

var app = express()
const app = express();
app.all(
"/graphql",
createHandler({
schema: schema,
schema,
rootValue: root,
})
)
app.listen(4000)
console.log("Running a GraphQL API server at localhost:4000/graphql")
);
app.listen(4000);
console.log("Running a GraphQL API server at localhost:4000/graphql");
```

If you run this code with `node server.js` and browse to http://localhost:4000/graphql you can try out these APIs.
Expand Down
72 changes: 38 additions & 34 deletions src/pages/graphql-js/constructing-types.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ When you are using the `GraphQLSchema` constructor to create a schema, instead o
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:

```js
var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
import express from "express";
import { createHandler } from "graphql-http/lib/use/express";
import { buildSchema } from "graphql";

var schema = buildSchema(`
const schema = buildSchema(`
type User {
id: String
name: String
Expand All @@ -22,10 +22,10 @@ var schema = buildSchema(`
type Query {
user(id: String): User
}
`)
`);

// Maps id to User object
var fakeDatabase = {
const fakeDatabase = {
a: {
id: "a",
name: "alice",
Expand All @@ -34,35 +34,39 @@ var fakeDatabase = {
id: "b",
name: "bob",
},
}
};

var root = {
const root = {
user({ id }) {
return fakeDatabase[id]
return fakeDatabase[id];
},
}
};

var app = express()
const app = express();
app.all(
"/graphql",
createHandler({
schema: schema,
schema,
rootValue: root,
})
)
app.listen(4000)
console.log("Running a GraphQL API server at localhost:4000/graphql")
);
app.listen(4000);
console.log("Running a GraphQL API server at localhost:4000/graphql");
```

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

```js
var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var graphql = require("graphql")
import express from "express";
import { createHandler } from "graphql-http/lib/use/express";
import {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
} from "graphql";

// Maps id to User object
var fakeDatabase = {
const fakeDatabase = {
a: {
id: "a",
name: "alice",
Expand All @@ -71,45 +75,45 @@ var fakeDatabase = {
id: "b",
name: "bob",
},
}
};

// Define the User type
var userType = new graphql.GraphQLObjectType({
const userType = new GraphQLObjectType({
name: "User",
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
id: { type: GraphQLString },
name: { type: GraphQLString },
},
})
});

// Define the Query type
var queryType = new graphql.GraphQLObjectType({
const queryType = new GraphQLObjectType({
name: "Query",
fields: {
user: {
type: userType,
// `args` describes the arguments that the `user` query accepts
args: {
id: { type: graphql.GraphQLString },
id: { type: GraphQLString },
},
resolve: (_, { id }) => {
return fakeDatabase[id]
return fakeDatabase[id];
},
},
},
})
});

var schema = new graphql.GraphQLSchema({ query: queryType })
const schema = new GraphQLSchema({ query: queryType });

var app = express()
const app = express();
app.all(
"/graphql",
createHandler({
schema: schema,
schema,
})
)
app.listen(4000)
console.log("Running a GraphQL API server at localhost:4000/graphql")
);
app.listen(4000);
console.log("Running a GraphQL API server at localhost:4000/graphql");
```

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.
Expand Down
31 changes: 22 additions & 9 deletions src/pages/graphql-js/graphql-clients.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,13 @@ fetch("/graphql", {
},
body: JSON.stringify({ query: "{ hello }" }),
})
.then(r => r.json())
.then(data => console.log("data returned:", data))
.then(response => response.json())
.then(data => {
console.log("Data returned:", data);
})
.catch(error => {
console.error("Request failed:", error);
});
```

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

```js
var dice = 3
var sides = 6
var query = /* GraphQL */`query RollDice($dice: Int!, $sides: Int) {
rollDice(numDice: $dice, numSides: $sides)
}`
const dice = 3;
const sides = 6;

const query = /* GraphQL */ `
query RollDice($dice: Int!, $sides: Int) {
rollDice(numDice: $dice, numSides: $sides)
}
`;

fetch("/graphql", {
method: "POST",
Expand All @@ -72,8 +80,13 @@ fetch("/graphql", {
variables: { dice, sides },
}),
})
.then(r => r.json())
.then(data => console.log("data returned:", data))
.then(response => response.json())
.then(data => {
console.log("Data returned:", data);
})
.catch(error => {
console.error("Request failed:", error);
});
```

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.
Expand Down
Loading