當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript express-graphql類代碼示例

本文整理匯總了TypeScript中express-graphql的典型用法代碼示例。如果您正苦於以下問題:TypeScript express-graphql類的具體用法?TypeScript express-graphql怎麽用?TypeScript express-graphql使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了express-graphql類的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: 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

示例2: 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

示例3: 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

示例4: 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

示例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類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。