Nodejs和Graphql的新手,正试图从api获取响应并使用graphgl进行过滤。但是在我从服务器获得响应之前已加载模块,尝试了await /,然后一切正常,不确定哪里出了问题,请提供您的建议
***My code setup:***
**// server.js**
const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./src/schema.js');
const PORT = process.env.PORT || 3000;
const app = express();
app.use('/', graphqlHTTP({
schema: schema,
graphiql: true //set to false if you don't want graphiql enabled
}));
app.listen(PORT);
console.log(`GraphQL API server running at localhost:${PORT}`);
///////////////////////////////////////////////// /////////////////////////
**//Schema.js**
const _ = require('lodash');
const express = require('express');
const request = require('request');
const Products = require('./data/products');
const app = express();
//console.log(Products);
/* Here a simple schema is constructed without using the GraphQL query language.
e.g. using 'new GraphQLObjectType' to create an object type
*/
let {
// These are the basic GraphQL types need in this tutorial
GraphQLString,
GraphQLList,
GraphQLObjectType,
// This is used to create required fileds and arguments
GraphQLNonNull,
// This is the class we need to create the schema
GraphQLSchema,
} = require('graphql');
const ProductsType = new GraphQLObjectType({
name: "Products",
description: "This represent a products api",
fields: () => ({
status: {type: new GraphQLNonNull(GraphQLString)},
})
});
// This is the Root Query
const BlogQueryRootType = new GraphQLObjectType({
name: 'BlogAppSchema',
description: "Blog Application Schema Root",
fields: () => ({
products: {
type: new GraphQLList(ProductsType),
description: "List of all Products",
resolve: function() {
return Products;
}
}
})
});
// This is the schema declaration
const BlogAppSchema = new GraphQLSchema({
query: BlogQueryRootType
// If you need to create or updata a datasource,
// you use mutations. Note:
// mutations will not be explored in this post.
// mutation: BlogMutationRootType
});
module.exports = BlogAppSchema;
///////////////////////////////////////////////// //////////////////////////////
**//Product.js**
const request = require('request');
// wrap a request in an promise
function downloadPage(url) {
return new Promise((resolve, reject) => {
request(url, (error, response, body) => {
if (error) reject(error);
if (response.statusCode != 200) {
reject('Invalid status code <' + response.statusCode + '>');
}
resolve(body);
});
});
}
// now to program the "usual" way
// all you need to do is use async functions and await
// for functions returning promises
async function myBackEndLogic() {
try {
const html = await downloadPage('http://someurl');
console.log('SHOULD WORK:');
return html;
} catch (error) {
console.error('ERROR:');
console.error(error);
}
}
// run your async function
module.exports = myBackEndLogic();