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(
function createMiddleware(
{ config, graphqlApi, logger, graphqlPath }: ExpressMiddlewareProps,
jwtVerify: Middleware,
): Middleware {
const isDev = config.env === "development";
const isProd = config.env === "production";
const PLAYGROUND_PATH = "/playground";
const VOYAGER_PATH = "/voyager";
const playground = playgroundMiddleware({ endpoint: graphqlPath });
const voyager = voyagerMiddleware({ endpointUrl: graphqlPath });
const router = Router();
const validationRules = [depthLimit(10)];
const schema = graphqlApi.getSchema();
const context = graphqlApi.getContext();
const allQueries = graphqlApi.getAllQueries();
const isIntrospectionQuery = (query: string): boolean => {
return Boolean(query && query.includes("query IntrospectionQuery {"));
};
if (!isDev) {
maskErrors(schema); // do not send internal errors to client
validationRules.push(NoIntrospection);
}
const apolloExpress = (req: $Request, res: $Response, next: NextFunction) => {
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;
import AuthenticationService from './AuthenticationService';
import AuthorizationService from './AuthorizationService';
import Database from './Database';
import HttpStatus from './utils/HttpStatus';
import { RateLimitError, JsonWebTokenError } from './utils/errors';
const IS_DEV = process.env.NODE_ENV === 'development';
const app = express();
app.disable('x-powered-by');
app.disable('etag');
app.use(bodyParser.json({ limit: '1kb' }));
app.use(cookieParser());
// Host graphql playground
app.get('/playground', expressPlayground({ endpoint: config.hasuraUrl }));
const database = new Database(config.database);
const authenticationService = new AuthenticationService(config.passcode);
const authorizationService = new AuthorizationService(
database,
config.accessToken,
config.refreshToken,
);
const emailHandler: RequestHandler = (req, res, next) => {
const email = req.body.email;
if (!email) {
return res
.status(HttpStatus.BAD_REQUEST)
.send('Missing field `email` of type string in post body.');
}
function setupGraphQL (app) {
app.use(GRAPHQL_ENDPOINT, graphqlExpress(req => {
return ({
schema,
// Set the context for all resolvers
context: {
// Current user
user: req.user,
},
// Apollo Engine flags
tracing: true,
cacheControl: false,
})
}))
app.use(PLAYGROUND_ENDPOINT, expressPlayground({
endpoint: GRAPHQL_ENDPOINT,
subscriptionEndpoint: SUBSCRIPTION_ENDPOINT,
}))
}
test('graphql-playground middleware handles error during project query read', async () => {
const config = mockConfig();
fs.readFile.mockImplementation((p, opts, cb) =>
cb(new Error(`ENOENT: ${p} not found`))
);
const middleware = jest.fn();
playgroundMiddleware.mockReturnValueOnce(middleware);
await PWADevServer.configure({ graphqlPlayground: true }, config);
expect(config.devServer.before).toBeInstanceOf(Function);
const app = {
get: jest.fn(),
use: jest.fn()
};
const compilerStatsData = {
stats: [
{
compilation: {
fileDependencies: new Set([
'path/to/module.js',
'path/to/query.graphql',
'path/to/otherModule.js',
};
config.devServer.before(app, server);
await waitForExpect(() => {
expect(app.get).toHaveBeenCalled();
});
const [endpoint, middlewareProxy] = app.get.mock.calls[0];
expect(endpoint).toBe('/graphiql');
expect(middlewareProxy).toBeInstanceOf(Function);
const req = {};
const res = {};
middlewareProxy(req, res);
await waitForExpect(() => {
expect(playgroundMiddleware).toHaveBeenCalled();
});
expect(fs.readFile).toHaveBeenCalledTimes(2);
expect(playgroundMiddleware.mock.calls[0][0]).toMatchObject({
endpoint: '/graphql',
tabs: [
{
endpoint: '/graphql',
name: 'path/to/query.graphql',
query: '{ foo { bar } }'
},
{
endpoint: '/graphql',
name: 'path/to/otherQuery.graphql',
query: '{ foo { bar, baz } }'
}
]
});
expect(middleware).toHaveBeenCalledWith(req, res, expect.any(Function));
config.devServer.after(app, server);
beforeEach(() => {
configureHost.mockReset();
portscanner.checkPortStatus.mockReset();
playgroundMiddleware.mockReset();
jest.spyOn(console, 'warn').mockImplementation();
jest.spyOn(console, 'log').mockImplementation();
});