簡體   English   中英

無法讀取未定義的屬性(讀取“findOne”)| 阿波羅服務器快遞 | 續集

[英]Cannot read properties of undefined (reading 'findOne') | apollo-server-express | sequelize

我被這個問題慢慢逼瘋了。

使用 Apollo Studio 訪問的本地 Apollo Server 實例,我正在嘗試一個簡單的突變,createUser,並且出現了這個問題。 我誤解了什么?

我是否錯誤地使用了我在創建服務器時提供的上下文? 或者錯誤地訪問了這個 model,也許? 不確定!

這是 Apollo Studio 中顯示的錯誤,后面是我的文件:

{
  "errors": [
    {
      "message": "Cannot read properties of undefined (reading 'findOne')",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "createUser"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: Cannot read properties of undefined (reading 'findOne')",
            "    at Object.createUser (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/graphql/resolvers/user.js:22:46)",
            "    at field.resolve (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/apollo-server-core/dist/utils/schemaInstrumentation.js:56:26)",
            "    at executeField (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/graphql/execution/execute.js:479:20)",
            "    at /Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/graphql/execution/execute.js:375:22",
            "    at promiseReduce (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/graphql/jsutils/promiseReduce.js:23:9)",
            "    at executeFieldsSerially (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/graphql/execution/execute.js:371:43)",
            "    at executeOperation (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/graphql/execution/execute.js:345:14)",
            "    at execute (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/graphql/execution/execute.js:136:20)",
            "    at execute (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/apollo-server-core/dist/requestPipeline.js:205:48)",
            "    at processGraphQLRequest (/Volumes/T7 Touch/Projects/PassTheArt/pass-the-art-server/node_modules/apollo-server-core/dist/requestPipeline.js:148:34)"
          ]
        }
      }
    }
  ],
  "data": null
}
// ./server.js
require('dotenv').config();
import express from 'express';
import db from './db';
import resolvers from './graphql/resolvers';
import typeDefs from './graphql/typeDefs';
import http from 'http';
import { ApolloServer } from 'apollo-server-express';

async function startApolloServer(){
    const server = new ApolloServer({
        typeDefs, 
        resolvers,
        introspection: true,
        playground: true,
        context: async() => {
            return {
                db
            }
        }
    });
    
    const app = express();
    const httpServer = http.createServer(app);
    
    server.start().then(res=>{
        server.applyMiddleware({app, path: '/graphql'});
        db.sequelize.sync({force: true}).then(async()=>{
            console.log('database synced');
        });
        httpServer.listen({port: process.env.PORT}, ()=>{
            console.log(`Apollo Server is ready at http://localhost:${process.env.PORT}/graphql`)
        })
    })
}

startApolloServer();

// ./graphql/resolvers/user.js
import { UserInputError } from "apollo-server-express";
import { Op } from "sequelize";

export default {
    Query: {
        // ! This query is for the logged in user
        me: async(root, args, {db, me}, info) => {
            const user = await db.user.findByPk(me.id);
            return user;
        },
        // ! This query returns all users
        users: async(root, args, {db}, info) => {
            const users = await db.user.findAll();
            if (!users) throw new Error('No users found')
            return users;
        }
    },
    Mutation: {
        // ! This mutation creates a new user
        createUser: async(root, {input}, {db}) => {
            const {email} = input;
            const userExists = await db.user.findOne({
                where: {
                    [Op.eq]: [{email}]
                }
            })
            if (userExists) {
                throw new Error('A user with this email already exists');
            }
            const user = await db.user.create({
                ...input
            });
            return user;
        },
        // ! 
        login: async(root, {email, password}, {db}, info) => {
            const user = await db.user.findOne({
                where: {email},
            });
            if(!user) throw new UserInputError(`User ${email} does not exist`);
            const isValid = await user.validatePassword(password);
            if(!isValid) throw new UserInputError(`Password is incorrect`);
            return user;
            
        }
    } 
}
// ./db.js
require('dotenv').config();
import fs from 'fs';
import path from 'path';
import { Sequelize } from 'sequelize';

const basename = path.basename(__filename);
const db = {};

const sequelize = new Sequelize(
    process.env.POSTGRES_DB,
    process.env.POSTGRES_USER,
    process.env.POSTGRES_PASSWORD,
    {
        host: process.env.POSTGRES_HOST,
        port: process.env.POSTGRES_PORT,
        dialect: 'postgres'
    }
);

sequelize.authenticate()
.then(console.log(()=>'Connection has been established successfully.'))
.catch(e=>console.error('Unable to connect to the database:', e));

const modelPath = path.join(__dirname, '/models');
fs.readdirSync(path.join(modelPath))
    .filter((file)=>
        file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js'
    )
    .forEach((file)=>{
        const model = sequelize.define(path.join(modelPath, file));
        db[model.name] = model;
    });
    
Object.keys(db).forEach((modelName)=>{
    if (db[modelName].associate){
        db[modelName].associate(db);
    }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

export default db;
// ./models/User.js
import bcrypt from 'bcryptjs';

export default (sequelize, DataTypes) => {
    const User = sequelize.define(
        'user',
        {
            name: {
                type: DataTypes.STRING,
                allowNull: false,
            },
            email: {
                type: DataTypes.STRING,
                allowNull: false,
                unique: true, 
                validate: {
                    isEmail: {
                        args: true,
                        msg: 'Invalid email'
                    },
                },
            },
            password: {
                type: DataTypes.STRING,
                allowNull: false,
            },
        },
        {
            freezeTableName: true,
        },
    );

    User.findByLogin = async (login) => {
        let user = await User.findOne({
            where: {email: login},
        });
        return user;
    };

    User.beforeCreate(async (user) => {
        if (user.password){
            user.password = await user.generatePasswordHash();
        }
    });

    User.prototype.updatePasswordHash = async function (password) {
        const saltRounds = 10;
        return await bcrypt.hash(password, saltRounds);
    };

    User.prototype.updatePasswordHash = async function () {
        const saltRounds = 10;
        return await bcrypt.hash(this.password, saltRounds);
    };

    User.prototype.validatePassword = async function (password) {
        return await bcrypt.compare(password, this.password);
    };

    return User;
}
// ./graphql/typedefs/User.js
import { gql } from "apollo-server-express";

export default gql`
    #---------------------------------------
    # TYPES
    #---------------------------------------
   
    type User {
        id: ID
        name: String!
        email: String!
    }

    #---------------------------------------
    # QUERIES
    #---------------------------------------
    
    extend type Query {
        me: User
        users: [User!]
    }

    #---------------------------------------
    # MUTATIONS
    #---------------------------------------

    extend type Mutation {
        createUser(input: CreateUserInput!): User!
        login(email: String!, password: String!): User!
        logout: User!
    }

    #---------------------------------------
    # MUTATIONS
    #---------------------------------------

    input CreateUserInput {
        name: String!
        email: String!
        password: String!
    }
`

您需要更正where選項

where: {
  [Op.eq]: [{email}]
}

where: {
  email
}

就像您在login突變中所做的一樣。

我設法正確定義了db.user.findOne 我沒有在db.js中正確使用sequelize.define() ,現在我已經重寫了討厭的部分:

const modelPath = path.join(__dirname, '/models');
fs.readdirSync(path.join(modelPath))
    .filter((file)=>
        file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js'
    )
    .forEach((file)=>{
        const modelFile = path.join(modelPath, file);
        const modelExport = require(modelFile);
        if (! modelExport) throw new Error ('Error accessing model declaration file: ', modelFile)
        const model = modelExport.default(sequelize);
        db[model.name] = model;
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM