How to use apollo-server-express - 10 common examples

To help you get started, we’ve selected a few apollo-server-express examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github luisw19 / graphql-samples / graphql-countries-part2 / server.js View on Github external
import resolvers from './resources/resolvers';

//Set Port. If environment variable exist use it instead
const GRAPHQL_PORT = process.env.GRAPHQL_PORT || 3000;

// Initialize the HTTP server using express
const server = express();

//Generate the executable schema. Note that makeExecutableSchema expects typeDefs and resolvers as input
const schema = makeExecutableSchema({
  typeDefs,
  resolvers
});

//Define the GraphQL endpoint using the Apollo GraphQL Server. Note that graphqlExress expects the schema constant
server.use('/graphql', bodyParser.json(), graphqlExpress({
  schema
}));

//Implement the Graphiql client available that comes with the Apollo GraphQL Server
server.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql'
}));

// Start the server
server.listen(GRAPHQL_PORT, () => {
  console.log('Go to http://localhost:' + GRAPHQL_PORT + '/graphiql to run queries!');
});
github hasura / graphql-schema-stitching-demo / index.js View on Github external
schema: hasuraGraphSchema,
    link: hasuraLink,
  });

  const finalSchema = mergeSchemas({
    schemas: [
      executableWeatherSchema,
      executableHasuraSchema,
      linkHasuraTypeDefs
    ],
    resolvers: hasuraWeatherResolvers
  });

  const app = new Express();

  app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: finalSchema}));

  app.use('/graphiql',graphiqlExpress({endpointURL: '/graphql'}));

  app.listen(8080);
  console.log('Server running. Open http://localhost:8080/graphiql to run queries.');
} // end of async run
github chnirt / nestjs-graphql-best-practice / src / config / graphql / schemaDirectives / permission.ts View on Github external
$map: {
									input: '$permissions.code',
									as: 'code',
									in: '$$code'
								}
							},
							_id: 0
						}
					}
				])
				.toArray()

			console.log(userRoles[0].permissions)

			if (userRoles[0].permissions.indexOf(permission) === -1) {
				throw new ForbiddenError('You are not authorized for this resource.')
			}

			// console.log('userRole', userRole)

			return resolve.apply(this, args)
		}
	}
github chnirt / nestjs-graphql-best-practice / src / config / graphql / schemaDirectives / permission.ts View on Github external
throw new AuthenticationError(
					'Authentication token is invalid, please try again.'
				)
			}

			// console.log(currentUser._id, permission)

			const role = await getMongoRepository(Role).find({
				where: {
					userId: currentUser._id,
					'permissions.code': permission
				}
			})

			if (!role) {
				throw new ForbiddenError('You are not authorized for this resource.')
			}

			// console.log('Role', role)

			return resolve.apply(this, args)
		}
	}
github chnirt / nestjs-graphql-best-practice / src / config / graphql / schemaDirectives / path.ts View on Github external
throw new AuthenticationError(
					'Authentication token is invalid, please try again.'
				)
			}

			// console.log(currentUser._id, path)

			const role = await getMongoRepository(Role).find({
				where: {
					userId: currentUser._id,
					path: { $regex: `.*${path}|${path.toLowerCase()}.*` },
				},
			})

			if (!role) {
				throw new ForbiddenError('You are not authorized for this resource.')
			}

			// console.log('Role', role)

			return resolve.apply(this, args)
		}
	}
github gatsbyjs / api.gatsbyjs.org / src / graphql / server.js View on Github external
if (process.env.NODE_ENV !== 'development') {
  // In production, make sure a valid token is present before doing anything.
  app.use(requireValidJWT);

  // If there’s an error, send it as JSON so it’s useful in the GraphQL output.
  app.use((err, _, res, next) => {
    if (err) {
      res.json(err);
    }

    next();
  });
}

// Set up the GraphQL server.
const server = new ApolloServer({
  typeDefs,
  resolvers,
  playground: process.env.NODE_ENV === 'development'
});

server.applyMiddleware({ app, cors: true });

// Turn the Express server into a lambda-compatible handler function.
const handler = serverless(app);

export const graphql = async (event, context) => {
  // Prevents Lambda cold starts
  if (event.source === 'serverless-plugin-warmup') {
    return 'Lambda is warm!';
  }
github jthegedus / firebase-functions-graphql-example / firebaseFunctions / graphql / server.js View on Github external
const setupGraphQLServer = () => {
  // setup server
  const graphQLServer = express()

  // /api/graphql
  graphQLServer.use(
    "/graphql",
    bodyParser.json(),
    graphqlExpress({ schema, context: {} })
  )

  // /api/graphiql
  graphQLServer.use(
    "/graphiql",
    graphiqlExpress({ endpointURL: "graphql" })
  )

  // /api/schema
  graphQLServer.use("/schema", (req, res) => {
    res.set("Content-Type", "text/plain")
    res.send(printSchema(schema))
  })

  return graphQLServer
}
github MoveOnOrg / Spoke / src / server / index.js View on Github external
app.get('/login-callback', ...loginCallbacks.loginCallback)
  app.post('/login-callback', ...loginCallbacks.loginCallback)
}

const executableSchema = makeExecutableSchema({
  typeDefs: schema,
  resolvers,
  allowUndefinedInResolve: false
})
addMockFunctionsToSchema({
  schema: executableSchema,
  mocks,
  preserveResolvers: true
})

app.use('/graphql', graphqlExpress((request) => ({
  schema: executableSchema,
  context: {
    loaders: createLoaders(),
    user: request.user,
    awsContext: request.awsContext || null,
    awsEvent: request.awsEvent || null,
    remainingMilliseconds: () => (
      (request.awsContext && request.awsContext.getRemainingTimeInMillis)
      ? request.awsContext.getRemainingTimeInMillis()
      : 5 * 60 * 1000 // default saying 5 min, no matter what
    )
  }
})))
app.get('/graphiql', graphiqlExpress({
  endpointURL: '/graphql'
}))
github reactioncommerce / reaction / server / graphql / server.js View on Github external
// something went bad when configuring the graphql server, we do not
        // swallow the error and display it in the server-side logs
        Logger.error(error, "[GraphQL Server] Something bad happened when handling a request on the GraphQL server");

        // return the default graphql options anyway
        return defaultGraphQLOptions;
      }
    })
  );

  // Start GraphiQL if enabled
  if (config.graphiql) {
    // GraphiQL endpoint
    expressServer.use(
      config.graphiqlPath,
      graphiqlExpress({
        // GraphiQL options
        ...config.graphiqlOptions,
        // endpoint of the graphql server where to send requests
        endpointURL: config.path
      })
    );
  }

  // bind the specified paths to the Express server running Apollo + GraphiQL
  WebApp.connectHandlers.use(expressServer);
}
github juicycleff / ultimate-backend / libs / core / src / cqrs / commands / handlers / auth / register-user.handler.ts View on Github external
async execute(command: RegisterUserCommand): Promise {
    Logger.log('Async RegisterUserHandler...', 'RegisterUserCommand');
    const { cmd } = command;

    try {

      const userExist: boolean = await this.userRepository.exist({
        'emails.address': cmd.email,
      });

      if (userExist) {
        throw new AuthenticationError('User with this authentication method already exist');
      }

      // @ts-ignore
      const user: UserEntity = {
        firstname: cmd.firstname,
        lastname: cmd.lastname,
        emails: [{
          address: cmd.email,
          primary: true,
          verified: false,
          verificationCode: generateVerificationCode(6, { type: 'number' }),
        }],
        roles: ['member'],
        services: {
          password: {
            hashed: cmd.password,