To run a GraphQL.js
hello world script from the command line:
npm install graphql
Then run node hello.js
with this code in hello.js
:
var { graphql, buildSchema } = require("graphql")
var schema = buildSchema(`
type Query {
hello: String
}
`)
var rootValue = { hello: () => "Hello world!" }
var source = "{ hello }"
graphql({ schema, source, rootValue }).then(response => {
console.log(response)
})
Relay is a JavaScript framework for building data-driven React applications.
To run a hello world server with Apollo Server:
npm install @apollo/server graphql
Then run node server.js
with this code in server.js
:
import { ApolloServer } from "@apollo/server"
import { startStandaloneServer } from "@apollo/server/standalone"
const server = new ApolloServer({
typeDefs,
resolvers,
})
const { url } = await startStandaloneServer(server)
console.log(`🚀 Server ready at ${url}`)
Apollo Server has a built in standalone HTTP server and middleware for Express, and has an framework integration API that supports all Node.js HTTP server frameworks and serverless environments via community integrations.
Apollo Server has a plugin API, integration with Apollo Studio, and performance and security features such as caching, automatic persisted queries, and CSRF prevention.
urql
is a GraphQL client that exposes a set of helpers for several frameworks.
It’s built to be highly customisable and versatile so you can take it from getting started with your first GraphQL project
all the way to building complex apps and experimenting with GraphQL clients.
@urql/exchange-graphcache
Request
& Response
objectsTo run a hello world server with graphql-yoga:
npm install graphql-yoga graphql
Then create a server using the createServer
import:
import { createServer } from "http"
import { createSchema, createYoga } from "graphql-yoga"
createServer(
createYoga({
schema: createSchema({
typeDefs: /* GraphQL */ `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => "Hello Hello Hello",
},
},
}),
}),
).listen(4000, () => {
console.info("GraphQL Yoga is listening on http://localhost:4000/graphql")
})
Depending on your deployment target, you may need to use an additional library. See the documentation for further details.
fetch
.GraphQL Shield helps you create a permission layer for your application. Using an intuitive rule-API, you’ll gain the power of the shield engine on every request and reduce the load time of every request with smart caching. This way you can make sure your application will remain quick, and no internal data will be exposed.
import { rule, shield, and, or, not } from "graphql-shield"
// Rules
const isAuthenticated = rule({ cache: "contextual" })(async (
parent,
args,
ctx,
info,
) => {
return ctx.user !== null
})
const isAdmin = rule({ cache: "contextual" })(async (
parent,
args,
ctx,
info,
) => {
return ctx.user.role === "admin"
})
const isEditor = rule({ cache: "contextual" })(async (
parent,
args,
ctx,
info,
) => {
return ctx.user.role === "editor"
})
// Permissions
const permissions = shield({
Query: {
frontPage: not(isAuthenticated),
fruits: and(isAuthenticated, or(isAdmin, isEditor)),
customers: and(isAuthenticated, isAdmin),
},
Mutation: {
addFruitToBasket: isAuthenticated,
},
Fruit: isAuthenticated,
Customer: isAdmin,
})
// Server
const server = new GraphQLServer({
typeDefs,
resolvers,
middlewares: [permissions],
context: req => ({
...req,
user: getUser(req),
}),
})
To run an hello world script with mercurius
:
npm install fastify mercurius
Then run node app.js
with this code in app.js
:
const Fastify = require("fastify")
const mercurius = require("mercurius")
const schema = `
type Query {
hello(name: String): String!
}
`
const resolvers = {
Query: {
hello: async (_, { name }) => `hello ${name || "world"}`,
},
}
const app = Fastify()
app.register(mercurius, {
schema,
resolvers,
})
app.listen(3000)
// Call IT!
// curl 'http://localhost:3000/graphql' \
// -H 'content-type: application/json' \
// --data-raw '{"query":"{ hello(name:\"Marcurius\") }" }'
GiraphQL makes writing type-safe schemas simple, and works without a code generator, build process, or extensive manual type definitions.
import { ApolloServer } from "apollo-server"
import SchemaBuilder from "@giraphql/core"
const builder = new SchemaBuilder({})
builder.queryType({
fields: t => ({
hello: t.string({
args: {
name: t.arg.string({}),
},
resolve: (parent, { name }) => `hello, ${name || "World"}`,
}),
}),
})
new ApolloServer({
schema: builder.toSchema({}),
}).listen(3000)
npm install graphql-hooks
First you’ll need to create a client and wrap your app with the provider:
import { GraphQLClient, ClientContext } from "graphql-hooks"
const client = new GraphQLClient({
url: "/graphql",
})
function App() {
return (
<ClientContext.Provider value={client}>
{/* children */}
</ClientContext.Provider>
)
}
Now in your child components you can make use of useQuery
:
import { useQuery } from "graphql-hooks"
const HOMEPAGE_QUERY = `query HomePage($limit: Int) {
users(limit: $limit) {
id
name
}
}`
function MyComponent() {
const { loading, error, data } = useQuery(HOMEPAGE_QUERY, {
variables: {
limit: 10,
},
})
if (loading) return "Loading..."
if (error) return "Something Bad Happened"
return (
<ul>
{data.users.map(({ id, name }) => (
<li key={id}>{name}</li>
))}
</ul>
)
}
GraphQL Middleware is a schema wrapper which allows you to manage additional functionality across multiple resolvers efficiently.
💡 Easy to use: An intuitive, yet familiar API that you will pick up in a second. 💪 Powerful: Allows complete control over your resolvers (Before, After). 🌈 Compatible: Works with any GraphQL Schema.
const { ApolloServer } = require("apollo-server")
const { makeExecutableSchema } = require("@graphql-tools/schema")
const typeDefs = `
type Query {
hello(name: String): String
bye(name: String): String
}
`
const resolvers = {
Query: {
hello: (root, args, context, info) => {
console.log(`3. resolver: hello`)
return `Hello ${args.name ? args.name : "world"}!`
},
bye: (root, args, context, info) => {
console.log(`3. resolver: bye`)
return `Bye ${args.name ? args.name : "world"}!`
},
},
}
const logInput = async (resolve, root, args, context, info) => {
console.log(`1. logInput: ${JSON.stringify(args)}`)
const result = await resolve(root, args, context, info)
console.log(`5. logInput`)
return result
}
const logResult = async (resolve, root, args, context, info) => {
console.log(`2. logResult`)
const result = await resolve(root, args, context, info)
console.log(`4. logResult: ${JSON.stringify(result)}`)
return result
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
const schemaWithMiddleware = applyMiddleware(schema, logInput, logResult)
const server = new ApolloServer({
schema: schemaWithMiddleware,
})
await server.listen({ port: 8008 })
SpectaQL is a Node.js library that generates static documentation for a GraphQL schema using a variety of options:
Out of the box, SpectaQL generates a single 3-column HTML page and lets you choose between a couple built-in themes. A main goal of the project is to be easily and extremely customizable—it is themeable and just about everything can be overridden or customized.
npm install --dev spectaql
# OR
yarn add -D spectaql
# Then generate your docs
npm run spectaql my-config.yml
# OR
yarn spectaql my-config.yml
GQty is a query builder, a query fetcher and a cache manager solution all-in-one.
You interact with your GraphQL endpoint via Proxy objects. Under the hood, GQty captures what is being read, checks cache validity, fetch missing contents and then updates the cache for you.
Start using GQty by simply running our interactive codegen:
# npm
npx @gqty/cli
# yarn
yarn dlx @gqty/cli
# pnpm
pnpm dlx @gqty/cli
GQty also provides framework specific integrations such as @gqty/react
and @gqty/solid
, which can be installed via our CLI.
npm create pylon@latest
to get started.npm create pylon@latest
Example service:
import { app } from "@getcronit/pylon"
class User {
name: string
email: string
constructor(name: string, email: string) {
this.name = name
this.email = email
}
}
const users = [
new User("Alice", "alice@example.com"),
new User("Bob", "bob@example.com"),
new User("Charlie", "charlie@example.com"),
]
export const graphql = {
Query: {
users,
user: (name: string) => {
return users.find(user => user.name === name)
},
},
Mutation: {
addUser: (name: string, email: string) => {
const user = new User(name, email)
users.push(user)
return user
},
},
}
export default app
query User {
user(name: "Alice") {
name
email
}
}
query Users {
users {
name
email
}
}
mutation AddUser {
addUser(name: "Corina", email: "corina@example.com") {
name
email
}
}
Microfiber is a JavaScript library that allows:
npm install microfiber
# OR
yarn add microfiber
Then in JS:
import { Microfiber } from "microfiber"
const introspectionQueryResults = {
// ...
}
const microfiber = new Microfiber(introspectionQueryResults)
// ...do some things to your schema with `microfiber`
const cleanedIntrospectonQueryResults = microfiber.getResponse()
The example below installs and initializes the GraphQLBox client with a persisted cache and debugging enabled.
npm install @graphql-box/core @graphql-box/client @graphql-box/request-parser @graphql-box/cache-manager @graphql-box/debug-manager @graphql-box/fetch-manager @graphql-box/helpers @cachemap/core @cachemap/reaper @cachemap/indexed-db @cachemap/constants @cachemap/types
import Cachemap from "@cachemap/core"
import indexedDB from "@cachemap/indexed-db"
import reaper from "@cachemap/reaper"
import CacheManager from "@graphql-box/cache-manager"
import Client from "@graphql-box/client"
import DebugManager from "@graphql-box/debug-manager"
import FetchManager from "@graphql-box/fetch-manager"
import RequestParser from "@graphql-box/request-parser"
import introspection from "./introspection-query"
const requestManager = new FetchManager({
apiUrl: "/api/graphql",
batchRequests: true,
logUrl: "/log/graphql",
})
const client = new Client({
cacheManager: new CacheManager({
cache: new Cachemap({
name: "client-cache",
reaper: reaper({ interval: 300000 }),
store: indexedDB(/* configure */),
}),
cascadeCacheControl: true,
typeCacheDirectives: {
// Add any type specific cache control directives in the format:
// TypeName: "public, max-age=3",
},
}),
debugManager: new DebugManager({
environment: "client",
log: (message, data, logLevel) => {
requestManager.log(message, data, logLevel)
},
name: "CLIENT",
performance: self.performance,
}),
requestManager,
requestParser: new RequestParser({ introspection }),
})
// Meanwhile... somewhere else in your code
const { data, errors } = await client.request(queryOrMutation)
The example below installs and initializes the GraphQLBox server with a persisted cache and debugging enabled.
npm install @graphql-box/core @graphql-box/server @graphql-box/client @graphql-box/request-parser @graphql-box/cache-manager @graphql-box/debug-manager @graphql-box/execute @graphql-box/helpers @cachemap/core @cachemap/reaper @cachemap/redis @cachemap/constants @cachemap/types
import Cachemap from "@cachemap/core"
import redis from "@cachemap/redis"
import reaper from "@cachemap/reaper"
import CacheManager from "@graphql-box/cache-manager"
import Client from "@graphql-box/client"
import DebugManager from "@graphql-box/debug-manager"
import Execute from "@graphql-box/execute"
import RequestParser from "@graphql-box/request-parser"
import Server from "@graphql-box/server"
import { makeExecutableSchema } from "@graphql-tools/schema"
import { performance } from "perf_hooks"
import { schemaResolvers, schemaTypeDefs } from "./schema"
import logger from "./logger"
const schema = makeExecutableSchema({
typeDefs: schemaTypeDefs,
resolvers: schemaResolvers,
})
const server = new Server({
client: new Client({
cacheManager: new CacheManager({
cache: new Cachemap({
name: "server-cache",
reaper: reaper({ interval: 300000 }),
store: redis(/* configure */),
}),
cascadeCacheControl: true,
typeCacheDirectives: {
// Add any type specific cache control directives in the format:
// TypeName: "public, max-age=3",
},
}),
debugManager: new DebugManager({
environment: "server",
log: (...args) => {
logger.log(...args)
},
name: "SERVER",
performance,
}),
requestManager: new Execute({ schema }),
requestParser: new RequestParser({ schema }),
}),
})
// Meanwhile... somewhere else in your code
app.use("api/graphql", graphqlServer.request())
Brangr - Browse Any Graph
Brangr is a simple, unique tool that any web server can host to provide a user-friendly browser/viewer for any GraphQL service (or many).
Brangr formats GraphQL results attractively, via a selection of user-configurable layouts. It lets users extract the generated HTML, and its source JSON. It provides a clever schema browser. It has built-in docs.
Brangr enables sites hosting it to present users with a collection of pre-fab GraphQL requests, which they can edit if desired, and let them create their own requests. And it allows sites to define custom CSS styling for all aspects of the formatted results.
Try it at the public Brangr site.
Example
query {
heroes(_layout: { type: table }) { # _layout arg not sent to service
first
last
}
}
Brangr renders the above query as follows (though not in a quote block):
heroes...
First Last Arthur Dent Ford Prefect Zaphod Beeblebrox