遵循GraphQL教程/解析器对象查询MySQL DB失败

时间:2019-06-24 21:01:18

标签: graphql apollo-server resolver

完全是本地开发的,我在这里遵循了该教程:https://scotch.io/tutorials/super-simple-graphql-with-node#toc-creating-the-graphql-server

几乎没有任何修改,只是将焦点限制在“产品”表上。没有“用户”或“配方”表。

看来我现在唯一的问题是从MySQL DB检索数据。

当然,我已经Google搜索并广泛比较了教程。我已经遍历了很多代码,以至于变得越来越模糊。

如果我将“ return”更改为{“ name”:“ test”},则数据将完美地传递到我的本地GraphQL仪表板。

models / index.js

'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
    sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
    sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs.readdirSync(__dirname).filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
}).forEach(file => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
}); //console.log(db);                                                                                                                                                      Object.keys(db).forEach(modelName => {                                                                                                                                    if (db[modelName].associate) {                                                                                                                                            db[modelName].associate(db);                                                                                                                                          }                                                                                                                                                                     });                                                                                                                                                                                                                                                                                                                                             db.sequelize = sequelize;                                                                                                                                               db.Sequelize = Sequelize;                                                                                                                                                                                                                                                                                                                       
module.exports = db;
'use strict';
module.exports = (sequelize, DataTypes) => {
    const Product = sequelize.define('Product', {
        name: DataTypes.STRING,
        urlWordRef: DataTypes.STRING,
        seoTitle: DataTypes.STRING,
        seoDescription: DataTypes.STRING,
        standardEquipment: DataTypes.STRING,
        technicalSpecs: DataTypes.STRING
    }, {});
    Product.associate = function(models) {
        // associations can be defined here
        //Product.hasMany(models.RefProductOptions)
    };
    return Product;
};  
// src/resolvers.js
const resolvers = {               
    Query: {
        async products (root, { id }, { models }) {
            return models.Products.findById(id) // *** THE LINE OF CODE WHICH FAILS ***
            return {"name":"test"} // ** SUBSTITUTING THE ABOVE LINE WITH THIS - SUCCESS!  ***
        }       
    }     
}                                    
module.exports = resolvers  
// src/schema.js
const { gql } = require('apollo-server')
const typeDefs = gql `
    type Products {
        id: Int!
        name: String
        urlWordRef: String
        seoTitle: String
        seoDescription: String
        standardEquipment: String
        technicalSpecs: String
    }
    type Query {
        products(id: Int!): Products
    }
`;
module.exports = typeDefs   
// src/index.js
const { ApolloServer } = require('apollo-server')
const typeDefs = require('./schema')
const resolvers = require('./resolvers')
const models = require('../models')
const server = new ApolloServer({
    typeDefs,
    resolvers,
    context: { models }
})
server.listen({port: 4000}).then(({ url }) => console.log('Server is running on localhost:4000'))  

通过仪表板查询GraphQL:

{
  products(id: 1) {
    name
  }
}

我希望我可以通过上面提到的GRaphQL查询传递ID,并获得正确的表行结果。

A,我准备用额头开始编码!


GraphQL中的错误响应:

{
  "errors": [
    {
      "message": "Cannot read property 'findById' of undefined",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "products"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: Cannot read property 'findById' of undefined",
            "    at products (/home/bob/graphql-server/src/resolvers.js:6:26)",
            "    at field.resolve (/home/bob/graphql-server/node_modules/graphql-extensions/dist/index.js:140:26)",
            "    at resolveFieldValueOrError (/home/bob/graphql-server/node_modules/graphql/execution/execute.js:486:18)",
            "    at resolveField (/home/bob/graphql-server/node_modules/graphql/execution/execute.js:453:16)",
            "    at executeFields (/home/bob/graphql-server/node_modules/graphql/execution/execute.js:294:18)",
            "    at executeOperation (/home/bob/graphql-server/node_modules/graphql/execution/execute.js:238:122)",
            "    at executeImpl (/home/bob/graphql-server/node_modules/graphql/execution/execute.js:85:14)",
            "    at Object.execute (/home/bob/graphql-server/node_modules/graphql/execution/execute.js:62:35)",
            "    at /home/bob/graphql-server/node_modules/apollo-server-core/dist/requestPipeline.js:239:46",
            "    at Generator.next (<anonymous>)",
            "    at /home/bob/graphql-server/node_modules/apollo-server-core/dist/requestPipeline.js:7:71",
            "    at new Promise (<anonymous>)",
            "    at __awaiter (/home/bob/graphql-server/node_modules/apollo-server-core/dist/requestPipeline.js:3:12)",
            "    at execute (/home/bob/graphql-server/node_modules/apollo-server-core/dist/requestPipeline.js:218:20)",
            "    at Object.<anonymous> (/home/bob/graphql-server/node_modules/apollo-server-core/dist/requestPipeline.js:156:42)",
            "    at Generator.next (<anonymous>)",
            "    at fulfilled (/home/bob/graphql-server/node_modules/apollo-server-core/dist/requestPipeline.js:4:58)",
            "    at <anonymous>",
            "    at process._tickCallback (internal/process/next_tick.js:188:7)"
          ]
        }
      }
    }
  ],
  "data": {
    "products": null
  }
}

0 个答案:

没有答案