Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const express = require("express");
const mongoose = require("mongoose");
const applyMiddleware = require("./middleware.js");
const graphqlHTTP = require("express-graphql"); // Express connecting package and naming convention
const schema = require("../schema/schema.js");
const expressPlayground = require("graphql-playground-middleware-express")
.default;
const server = express(); // Create new server
require("dotenv").config();
const restricted = require("../auth/restricted.js");
applyMiddleware(server);
server.get("/playground", expressPlayground({ endpoint: "/graphql" })); // Use GraphQL Playground
server.get("/", (req, res) => {
res.send("The server is alive and well 🎉");
});
// Connect to MongoDB Atlas database
mongoose.connect(process.env.DB_URI, { useNewUrlParser: true });
mongoose.connection.once("open", () => {
console.log(`
Connected to MongoDB Database Cluster
------------------------------------------------------------
`);
});
// Server use GraphQL with /graphql endpoint
server.use(
graphiql: serverOptions.graphiql || false,
context: {
request,
response,
},
customFormatErrorFn: (error: GraphQLError) => ({
...error,
trace: process.env.NODE_ENV !== "production" ? error.stack : null
})
})),
)
// setup playground
if (serverOptions.playground) {
const expressPlayground = require('graphql-playground-middleware-express').default
expressApp.get('/playground', expressPlayground({
endpoint: serverOptions.route || "/graphql",
subscriptionsEndpoint: `ws://localhost:${serverOptions.websocketPort}/${serverOptions.subscriptionsRoute || "subscriptions"}`
}))
}
// run websocket server
if (serverOptions.websocketPort) {
const websocketServer = createServer((request, response) => {
response.writeHead(404);
response.end();
})
websocketServer.listen(serverOptions.websocketPort, () => {})
new SubscriptionServer(
{ schema, execute, subscribe },
app.get('/graphiql', async (req, res) => {
if (!middleware) {
middleware = playgroundMiddleware({
endpoint,
tabs: await gatheringQueryTabs
});
}
// this middleware has a bad habit of calling next() when it
// should not, so let's give it a noop next()
middleware(req, res, noop);
});
};
const express = require('express');
const applyMiddleware = require('./middleware.js');
const graphqlHTTP = require('express-graphql'); // Express connecting package and naming convention
const schema = require('../schema/schema.js');
const expressPlayground = require('graphql-playground-middleware-express')
.default; // Custom middleware replacement of Graphiql with GraphQL Playground
const server = express();
applyMiddleware(server);
server.get('/playground', expressPlayground({ endpoint: '/graphql' })); // Use GraphQL Playground
server.get('/', (req, res) => {
res.send('The Server is alive and well 🎉');
});
// Server use GraphQL with /graphql endpoint
server.use(
'/graphql',
graphqlHTTP({
schema,
graphiql: false // Turns off graphiql for GraphQL Playground use
})
);
module.exports = server;
validationRules: [
depthLimit(5),
createComplexityLimitRule(1000, {
onCost: cost => console.log('query cost: ', cost)
})
],
context: async ({ req, connection }) => {
const githubToken = req ? req.headers.authorization : connection.context.Authorization
const currentUser = await db.collection('users').findOne({ githubToken })
return { db, currentUser, pubsub }
}
})
server.applyMiddleware({ app })
app.get('/playground', expressPlayground({ endpoint: '/graphql' }))
app.get('/', (req, res) => {
let url = `https://github.com/login/oauth/authorize?client_id=${process.env.CLIENT_ID}&scope=user`
res.end(`<a href="${url}">Sign In with Github</a>`)
})
app.use(
'/img/photos',
express.static(path.join(__dirname, 'assets', 'photos'))
)
const httpServer = createServer(app)
server.installSubscriptionHandlers(httpServer)
httpServer.timeout = 5000
httpServer.listen({ port: 4000 }, () =>
schema {
query: Query
}
`,
resolvers: {
Query: {
hello: () => 'world',
},
},
})
const PORT = 4001
const app = express()
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }))
app.get('/playground', expressPlayground({ endpoint: '/graphql', env: process.env, useGraphQLConfig: true}))
app.listen(PORT)
console.log(
`Serving the GraphQL Playground on http://localhost:${PORT}/playground`,
)
const port = 4000
const app = express()
const schema = makeExecutableSchema({ typeDefs, resolvers })
app.use(
'/graphql',
cors(),
bodyParser.json(),
persistedQueries,
graphqlExpress({ schema })
)
app.use(
'/playground',
playground({ endpointUrl: '/graphql' })
)
app.listen(port, () => console.log(`listening on port: ${port}`))
const page = app.pages._pages.findOne({
path: variables.__path
})
return {
context: page ? page.context : {}
}
}
}
})
)
if (options.withExplorer) {
server.get(
endpoint.explore,
playground({
endpoint: endpoint.graphql,
title: 'Gridsome GraphQL Explorer',
faviconUrl: 'https://avatars0.githubusercontent.com/u/17981963?s=200&v=4'
})
)
}
const assetsDir = path.relative(config.outDir, config.assetsDir)
const assetsPath = forwardSlash(path.join(config.pathPrefix, assetsDir))
const assetsRE = new RegExp(`${assetsPath}/(files|static)/(.*)`)
server.get(assetsRE, require('./middlewares/assets')(app))
const createUrl = (endpoint, protocol = 'http') => {
return `${protocol}://${config.host}:${port}${forwardSlash(endpoint)}`
}
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post(
'/graphql',
cors(corsOptions),
credentials(),
bodyParserGraphql.graphql({
limit: '1mb',
}),
);
if (cfg.app.playground) {
app.get(
'/playground',
cors(corsOptions),
playground({
endpoint: '/graphql',
subscriptionsEndpoint: '/subscription',
}),
);
}
passport.serializeUser((user, done) => {
const { identityProviderId, identity } = user;
return done(null, {
identityProviderId,
identity,
});
});
passport.deserializeUser((obj, done) => {
return done(null, obj);
async function boot() {
logger.info("Apollon is starting");
app.use(cors(config.cors));
app.use(
"/playground",
expressPlayground.default({
endpoint: config.endpoint || "/",
SubscriptionEndpoint: `ws://localhost:3000/subscriptions`
}),
() => {}
);
logger.debug("- Endpoint /playground is accessible");
app.use(
config.endpoint || "/",
bodyParser.json(),
...middlewares,
graphqlExpress(async (request, response) => {
return {
context: {
PORT,
ENDPOINT: config.endpoint || "/",