express-graphql#graphqlHTTP TypeScript Examples

The following examples show how to use express-graphql#graphqlHTTP. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
express()
    .use(cors())
    .use(
        '/graphql', 
        graphqlHTTP({
            schema,
            graphiql: true,
            customFormatErrorFn: err => {
                console.log("Exception raised!", err);
                return err;
            }
        })
    )
    .listen(8080, () => {
        console.log("\n\n\nGraphQL server is started, please access http://localhost:8080/graphql");
    });
Example #2
Source File: index.ts    From payload with MIT License 6 votes vote down vote up
init(req, res) {
    this.errorResponses = null;
    return graphqlHTTP(
      async (request, response, { variables }) => ({
        schema: this.schema,
        customFormatErrorFn: this.customFormatErrorFn,
        extensions: this.extensions,
        context: { req, res },
        validationRules: this.validationRules(variables),
      }),
    );
  }
Example #3
Source File: application.ts    From mikro-orm-graphql-example with MIT License 5 votes vote down vote up
public init = async (): Promise<void> => {
    this.host = express();

    if (process.env.NODE_ENV !== 'production') {
      this.host.get('/graphql', expressPlayground({ endpoint: '/graphql' }));
    }

    this.host.use(cors());

    try {
      const schema: GraphQLSchema = await buildSchema({
        resolvers: [BookResolver, AuthorResolver],
        dateScalarMode: 'isoDate',
      });

      this.host.post(
        '/graphql',
        bodyParser.json(),
        graphqlHTTP((req, res) => ({
          schema,
          context: { req, res, em: this.orm.em.fork() } as MyContext,
          customFormatErrorFn: (error) => {
            throw error;
          },
        })),
      );

      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      this.host.use((error: Error, req: express.Request, res: express.Response, next: express.NextFunction): void => {
        console.error('? Something went wrong', error);
        res.status(400).send(error);
      });

      const port = process.env.PORT || 4000;
      this.server = this.host.listen(port, () => {
        console.log(`? http://localhost:${port}/graphql`);
      });
    } catch (error) {
      console.error('? Could not start server', error);
    }
  };
Example #4
Source File: router.ts    From peterportal-public-api with MIT License 5 votes vote down vote up
router.use('/', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));
Example #5
Source File: graphql.ts    From react-js-tutorial with MIT License 5 votes vote down vote up
app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    rootValue: root,
    graphiql: true,
  })
);
Example #6
Source File: createGraphQLServer.ts    From davinci with MIT License 4 votes vote down vote up
createGraphQLServer = (
	app: DaVinciExpress,
	controllers: ClassType[],
	options?: ICreateGraphQLServerOptions
) => {
	const { context, graphqlEndpoint, graphqlOptions, playgroundEnabled, playgroundOptions } = _.merge(
		{},
		DEFAULT_OPTIONS,
		options
	);

	const allSchemas = { queries: {}, mutations: {}, schemas: {} };
	const { queries: queryFields, mutations: mutationsFields } = (controllers || []).reduce(
		(acc, controller) => {
			_.merge(allSchemas, acc.schemas);
			const { queries, mutations, schemas } = createControllerSchemas(controller, allSchemas);
			if (queries) {
				acc.queries = _.merge({}, acc.queries || {}, queries);
			}
			if (mutations) {
				acc.mutations = _.merge(acc.mutations || {}, mutations);
			}
			if (schemas) {
				acc.schemas = _.merge(acc.schemas || {}, schemas);
			}
			return acc;
		},
		{ queries: null, mutations: null, schemas: null }
	);

	const schema = new GraphQLSchema({
		query: queryFields
			? new GraphQLObjectType({
					name: 'Query',
					fields: {
						...queryFields
					}
			  })
			: null,
		mutation: !_.isEmpty(mutationsFields)
			? new GraphQLObjectType({
					name: 'Mutation',
					fields: {
						...mutationsFields
					}
			  })
			: null
	});

	if (playgroundEnabled) {
		// tslint:disable-next-line:variable-name
		app.get(graphqlEndpoint, (_req, res) => res.send(playground(playgroundOptions)));
	}

	app.use(
		graphqlEndpoint,
		graphqlHTTP(async request => {
			const ctx = typeof context === 'function' ? await context(request) : context;
			return {
				schema,
				graphiql: false,
				context: ctx,
				...(graphqlOptions || {})
			};
		})
	);
	console.info(`--- ? GraphQL running on ${graphqlEndpoint}`);

	if (playgroundEnabled) {
		console.info(`--- ? GraphQL Playground on ${graphqlEndpoint}`);
	}

	const printSDL = () => printSchema(schema);

	const writeSDLtoFile = async path => {
		const sdl = printSDL();
		await fs.promises.writeFile(path, sdl);
	};

	return { app, schema, printSDL, writeSDLtoFile };
}
Example #7
Source File: index.ts    From server with Apache License 2.0 4 votes vote down vote up
(async () => {
  logger.info(`Server version: ${  version.buildMajor  }.${  version.buildMinor  }.${  version.buildRevision}`)
  logger.info(`Arguments: ${  process.argv}`)
  
  // Construct a schema, using GraphQL schema language
  const typeDefs = await importSchema('./schema/index.graphql'); 
  const schema = await makeExecutableSchema({ typeDefs, resolvers })

  await initModels();

  let channelTypes = undefined
  
  if (process.env.OPENPIM_KEY) {
    const keyData = 
`-----BEGIN RSA PUBLIC KEY-----
MEgCQQDG0oEGhlYcN12BqBeMn9aRwfrPElOol7prVUQNAggZjurOQ5DyjbPh9uOW
XWhRphP+pl2nJQLVRu+oDpf2wKc/AgMBAAE=
-----END RSA PUBLIC KEY-----
`
    const publicKey: crypto.KeyObject = crypto.createPublicKey({key: keyData, type: 'pkcs1', format: 'pem'})
    const str = Buffer.from(process.env.OPENPIM_KEY, 'base64').toString('ascii')
    const idx = str.lastIndexOf('|')
    const sign = str.substring(idx+1)
    const data = str.substring(0, idx)
    const split = data.split('|')
    const options: any = { key: publicKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING }
    const isVerified = crypto.verify( "sha256", Buffer.from(data), options, Buffer.from(sign, 'base64'))
    if (isVerified) {
      channelTypes = JSON.parse("[" + split[0] + "]")
      logger.info('Found key for company: ' + split[1]+' with data: '+channelTypes)
    } else {
      logger.error('Wrong key')
      channelTypes = []
    }
  }

  ModelsManager.getInstance().init(channelTypes)
  ChannelsManagerFactory.getInstance().init()
  
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(cors());
  
  app.use('/graphql', graphqlHTTP(async (request: IncomingMessage ) => ({
    schema,
    graphiql: false,
    context: await Context.create(request),
    customFormatErrorFn: (error: GraphQLError) => {
      const params = {
        message: error.message
      };
      logger.error('ERROR -', error, error.source);
      logger.error(`   request - ${ JSON.stringify((<any>request).body)}`);
      return (params);
    }
  })));

  app.get('/healthcheck', async (req, res) => {
    res.json({result: "OK"})
  })

  app.post('/asset-upload', async (req, res) => {
    try {
      const context = await Context.create(req)
      context.checkAuth()

      await processUpload(context, req, res)
    } catch (error: any) {
      res.status(400).send(error.message)
    }
  })

  app.post('/asset-create-upload', async (req, res) => {
    try {
      const context = await Context.create(req)
      context.checkAuth()

      await processCreateUpload(context, req, res)
    } catch (error: any) {
      res.status(400).send(error.message)
    }
  })

  app.get('/asset/:id', async (req, res) => {
    try {
      const context = await Context.create(req)
      await processDownload(context, req, res, false)
    } catch (error: any) {
      res.status(400).send(error.message)
    }
  })

  app.get('/asset/:id/thumb', async (req, res) => {
    try {
      const context = await Context.create(req)
      context.checkAuth()
      await processDownload(context, req, res, true)
    } catch (error: any) {
      res.status(400).send(error.message)
    }
  })

  app.get('/asset-channel/:id', async (req, res) => {
    try {
      const context = await Context.create(req)
      context.checkAuth()
      await processChannelDownload(context, req, res, false)
    } catch (error: any) {
      res.status(400).send(error.message)
    }
  })

  app.listen(process.env.PORT);
  logger.info('Running a GraphQL API server at http://localhost:' + process.env.PORT + '/graphql');
})();
Example #8
Source File: server.ts    From client-side-databases with Apache License 2.0 4 votes vote down vote up
export async function run() {
    const startData = exampleData;
    const state: {
        users: WithDeleted<User>[],
        messages: WithDeleted<Message>[]
    } = {
        users: startData.users.map(user => {
            const userWithDeleted = Object.assign({ deleted: false }, user);
            return userWithDeleted;
        }),
        messages: []
    };
    // to faster access all messages for a specific user,
    // we index the message by user-id here
    const messagesByUser: { [userId: string]: Message[] } = {};
    const getMessageArrayOfUser = (userId: string) => {
        if (!messagesByUser[userId]) {
            messagesByUser[userId] = [];
        }
        return messagesByUser[userId];
    };
    const addMessageToState = (message: Message) => {
        const messageWithDeleted = Object.assign({ deleted: false }, message);
        state.messages.push(messageWithDeleted);
        getMessageArrayOfUser(message.sender).push(message);
        getMessageArrayOfUser(message.reciever).push(message);
    };

    const app: Express = express();
    // cache options request
    app.options('*', (req, res, done) => {
        if (req.method === 'OPTIONS') {
            log('OPTIONS request');
            const headers = {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
                'Access-Control-Allow-Credentials': 'false',
                'Access-Control-Max-Age': '86400',
                'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
            };
            res.writeHead(200, headers);
            res.end();
        } else {
            done();
        }
    });
    app.use(cors());


    const generatedSchema = graphQLSchemaFromRxSchema({
        users: {
            schema: RxUsersSchema,
            feedKeys: [
                'id',
                'createdAt'
            ],
            deletedFlag: 'deleted'
        },
        messages: {
            schema: RxMessagesSchema,
            feedKeys: [
                'id',
                'createdAt'
            ],
            deletedFlag: 'deleted'
        }
    });
    const graphQLSchema = generatedSchema.asString;
    console.log('GraphQL schema:');
    console.log(graphQLSchema);
    const schema = buildSchema(graphQLSchema);

    const pubsub = new PubSub();

    // The root provides a resolver function for each API endpoint
    const root = {
        info: () => 1,
        feedUsers: (args: any) => {
            log('## feedUsers()');
            console.dir(args);
            const users = state.users;
            const ret = filterForFeedResult(
                users,
                args.createdAt,
                args.id,
                args.limit
            );
            log('got ' + ret.length + ' users');
            return ret;
        },
        feedMessages: (args: any) => {
            log('## feedMessages()');
            const ret = filterForFeedResult(
                state.messages,
                args.createdAt,
                args.id,
                args.limit
            );
            console.dir(args);
            log('got ' + ret.length + ' messages');
            return ret;
        },
        setMessages: (args: {
            messages: Message[]
        }) => {
            const messages: Message[] = args.messages;
            messages.forEach(message => {
                log('## addMessage() ' + message.id + ' from ' + message.sender);

                // overwrite timestamp
                message.createdAt = unixInSeconds();

                // log(message);
                addMessageToState(message);

                pubsub.publish(
                    'changedMessages',
                    {
                        changedMessages: message
                    }
                );
            });
        },
        setUsers: (args: any) => {
            log('## registerUser()');
            const time = (new Date().getTime() / 1000);
            const user = {
                id: 'u' + time,
                name: args.name,
                createdAt: time,
                deleted: false
            };

            state.users.push(user);
            pubsub.publish(
                'changedUsers',
                {
                    changedUsers: user
                }
            );
            return user;
        },
        changedUsers: () => pubsub.asyncIterator('changedUsers'),
        changedMessages: () => pubsub.asyncIterator('changedMessages')
    };

    // add start-messages to state
    root.setMessages({
        messages: startData.messages
    });


    // server graphql-endpoint
    app.use(GRAPHQL_PATH, graphqlHTTP({
        schema,
        rootValue: root,
        graphiql: true,
    }));

    app.listen(GRAPHQL_PORT, () => {
        log('Started graphql-endpoint at http://localhost:' +
            GRAPHQL_PORT + GRAPHQL_PATH
        );
    });

    const appSubscription = express();
    appSubscription.use(cors);
    const serverSubscription = createServer(appSubscription);
    serverSubscription.listen(GRAPHQL_SUBSCRIPTION_PORT, () => {
        log(
            'Started graphql-subscription endpoint at http://localhost:' +
            GRAPHQL_SUBSCRIPTION_PORT + GRAPHQL_SUBSCRIPTION_PATH
        );
        const subServer = new SubscriptionServer(
            {
                execute,
                subscribe,
                schema,
                rootValue: root
            },
            {
                server: serverSubscription,
                path: GRAPHQL_SUBSCRIPTION_PATH,
            }
        );
        return subServer;
    });


    // comment this in for testing of the subscriptions
    /*
    setInterval(() => {
        const flag = new Date().getTime();
        pubsub.publish(
            'humanChanged',
            {
                humanChanged: {
                    id: 'foobar-' + flag,
                    name: 'name-' + flag
                }
            }
        );
        console.log('published humanChanged ' + flag);
    }, 1000);*/
}