当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript express-graphql.default方法代码示例

本文整理汇总了TypeScript中express-graphql.default方法的典型用法代码示例。如果您正苦于以下问题:TypeScript express-graphql.default方法的具体用法?TypeScript express-graphql.default怎么用?TypeScript express-graphql.default使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在express-graphql的用法示例。


在下文中一共展示了express-graphql.default方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: runServer

function runServer(schemaIDL: Source, extensionIDL: Source, optionsCB) {
  const app = express();

  if (extensionIDL) {
    const schema = buildServerSchema(schemaIDL);
    extensionIDL.body = extensionIDL.body.replace('<RootTypeName>', schema.getQueryType().name);
  }
  app.options('/graphql', cors(corsOptions))
  app.use('/graphql', cors(corsOptions), graphqlHTTP(() => {
    const schema = buildServerSchema(schemaIDL);

    return {
      ...optionsCB(schema, extensionIDL),
      graphiql: true,
    };
  }));

  app.get('/user-idl', (_, res) => {
    res.status(200).json({
      schemaIDL: schemaIDL.body,
      extensionIDL: extensionIDL && extensionIDL.body,
    });
  });

  app.use('/user-idl', bodyParser.text());

  app.post('/user-idl', (req, res) => {
    try {
      if (extensionIDL === null)
        schemaIDL = saveIDL(req.body);
      else
        extensionIDL = saveIDL(req.body);

      res.status(200).send('ok');
    } catch(err) {
      res.status(500).send(err.message)
    }
  });

  app.use('/editor', express.static(path.join(__dirname, 'editor')));

  app.listen(argv.port);

  log(`\n${chalk.green('✔')} Your GraphQL Fake API is ready to use 🚀
  Here are your links:

  ${chalk.blue('❯')} Interactive Editor:\t http://localhost:${argv.port}/editor
  ${chalk.blue('❯')} GraphQL API:\t http://localhost:${argv.port}/graphql

  `);

  if (!fileArg) {
    log(chalk.yellow(`Default file ${chalk.magenta(fileName)} is used. ` +
    `Specify [file] parameter to change.`));
  }

  if (argv.open) {
    setTimeout(() => opn(`http://localhost:${argv.port}/editor`), 500);
  }
}
开发者ID:codeaudit,项目名称:graphql-faker,代码行数:60,代码来源:index.ts

示例2: async

const run = async () => {
  const schema = await buildSchema({
    resolvers: [UserResolver],
    emitSchemaFile: path.resolve(__dirname, 'schema.gql')
  })

  const app = express()
  app.use('/graphql', grapqlHTTP({
    schema,
    graphiql: true
  }))

  app.listen(process.env.PORT || 3000)
}
开发者ID:uldissturms,项目名称:playgrounds,代码行数:14,代码来源:index.ts

示例3: GraphQLHTTP

 app.use('/graphql', (req: express.Request, res: express.Response) => {
     // Creates a GraphQLHTTP per request
     GraphQLHTTP({
         schema: Schema.get(),
         rootValue: new RootValue(),
         context: new Context(
             req, res,
             DataLoadersContext.getInstance(),
             ServicesContext.getInstance()
         ),
         graphiql: Environment.getConfig().server.graphiql,
         formatError: exception => ({
             name: Exception.getName(exception.message),
             message: Exception.getMessage(exception.message),
             path: exception.path
         })
     })(req, res);
 });
开发者ID:w3tecch,项目名称:node-ts-boilerplate,代码行数:18,代码来源:GraphQLRoutes.ts

示例4: express

import * as express from "express";
import 'express-session';
import * as graphqlHTTP from "express-graphql";

const app = express();
const schema = {};

const graphqlOption: graphqlHTTP.OptionsObj = {
    graphiql: true,
    schema: schema,
    formatError: (error:Error) => ({
        message: error.message,
    })
};

const graphqlOptionRequest = (request: express.Request): graphqlHTTP.OptionsObj => ({
    graphiql: true,
    schema: schema,
    context: request.session,
});

app.use("/graphql1", graphqlHTTP(graphqlOption));

app.use("/graphql2", graphqlHTTP(graphqlOptionRequest));

app.listen(8080);
开发者ID:ArtemZag,项目名称:DefinitelyTyped,代码行数:26,代码来源:express-graphql-tests.ts

示例5: GraphQLHTTP

// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', (req, res) => res.sendFile(path.join(__dirname, '/public/test.html')))

//Initialize Parse
Parse.initialize(APP_ID)
Parse.serverURL = SERVER_URL
Parse.masterKey = MASTER_KEY
Parse.Cloud.useMasterKey()

//GraphQL
app.use('/graphql', GraphQLHTTP((request) => ({
    graphiql: true,
    pretty: true,
    schema,
    context: {
        sessionToken: request.headers[ 'x-parse-session-token' ],
    },
})))

app.use('/graph', middleware({ endpointUrl: '/graphql' }));


const httpServer = require('http').createServer(app)
httpServer.listen(port, () => {
    console.log(`StaticServer running on ${SERVER_URL.replace('/parse','/')}`)
    console.log(`Parse Server running on ${SERVER_URL}`)
    console.log(`Graphql running on ${SERVER_URL.replace('/parse','/graphql')}`)
    console.log(`Graphql Visual running on ${SERVER_URL.replace('/parse','/graph')}`)
})
开发者ID:movibe,项目名称:parse-server-example,代码行数:30,代码来源:index.ts

示例6: GraphQLSchema

const tempSchema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      donnyData: {
        type: GraphQLString,
        resolve() {
          return 'hello world';
        }
      }
    }
  })
})

app.use('/graphql', graphqlHTTP({ schema: tempSchema, graphiql: true }))


// Mongoose tests


import * as mongoose from 'mongoose'
import * as Promise from 'bluebird'

 mongoose.Promise = Promise
    // assert.equal(query.exec().constructor, require('bluebird'));

mongoose.connect(databaseUri)

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'))
开发者ID:zleman1593,项目名称:parse-server-transform-bug,代码行数:30,代码来源:index.ts

示例7: async

const graphqlOption: graphqlHTTP.OptionsObj = {
    graphiql: true,
    schema: schema,
    formatError: (error: Error) => ({
        message: error.message
    })
};

const graphqlOptionRequest = (request: express.Request): graphqlHTTP.OptionsObj => ({
    graphiql: true,
    schema: schema,
    context: request.session
});

const graphqlOptionRequestAsync = async (request: express.Request): Promise<graphqlHTTP.OptionsObj> => {
    return {
        graphiql: true,
        schema: await Promise.resolve(schema),
        context: request.session
    };
};

app.use('/graphql1', graphqlHTTP(graphqlOption));

app.use('/graphql2', graphqlHTTP(graphqlOptionRequest));

app.use('/graphqlasync', graphqlHTTP(graphqlOptionRequestAsync));

app.listen(8080, () => console.log('GraphQL Server running on localhost:8080'));
开发者ID:AbraaoAlves,项目名称:DefinitelyTyped,代码行数:29,代码来源:express-graphql-tests.ts

示例8: makeExecutableSchema

export const schema = makeExecutableSchema({
  typeDefs: importSchema(`${dirname}/index.graphql`),
  resolvers: [
    SampleService.resolvers,
  ],
});

const middleware = graphqlHTTP((request, response?, graphQLParams?) => {
  if (graphQLParams) {
    request.body = {
      query: graphQLParams.query && graphQLParams.query.replace(/\s+/g, ' '),
      variables: graphQLParams.variables,
      operationName: graphQLParams.operationName,
    };
  }
  return {
    schema,
    graphiql: process.env.NODE_ENV !== 'production',
    extensions: ({ result }) => {
      (response as any).errors = result.errors;
      return {};
    },
  };
});

export async function handler(request, response) {
  const start = new Date();
  response.on('finish', () => {
    const end = new Date();
    let message = 'OK';
    if (response.statusCode >= 300) {
开发者ID:june1123,项目名称:testSources,代码行数:31,代码来源:index.ts

示例9: Promise

router.use(GraphQLHTTP(
    (req: Request, res: Response): Promise<any> => {
        return new Promise((resolve, reject) => {
            const next = (user: IUser, info = {}) => {
                /**
                 * GraphQL configuration goes here
                 */
                resolve({
                    schema,
                    graphiql: config.get("isDev"), // <- only enable GraphiQL in production
                    pretty: config.get("isDev"),
                    context: {
                        user: user || null,
                    },
                    formatError: (error: any): any => ({
                        message: error.message,
                        state: error.originalError && error.originalError.state,
                        path: error.path,
                        status:error.status||500
                    })
                });
            };
            /**
             * Try to authenticate using passport,
             * but never block the call from here.
             */
            passport.authenticate(["access","refresh","local"], { session: false }, (err, loginOptions) => {
                next(loginOptions);
            })(req, res, next);
        })
    }));
开发者ID:ZulusK,项目名称:Budgetarium,代码行数:31,代码来源:index.ts


注:本文中的express-graphql.default方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。