本文整理汇总了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);
示例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);
}
}
示例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)
}
示例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);
});
示例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')}`)
})
示例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:'))
示例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'));
示例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) {
示例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);
})
}));