0

一旦我将任何代码添加到我的用于在 MongoDB 中查询和变异数据的特定解析器中,我就会不断从我的服务器收到未处理的承诺拒绝错误。解析器的代码如下所示:

import { Coordinates, Fridge, Fridges } from '../models/Fridge';
import { Arg, Ctx, Field, InputType, Mutation, Resolver } from 'type-graphql';
import { MyContext } from '../types';
import { Users } from '../models/User';

@InputType()
class FridgeInput {
  @Field()
  name: string

  @Field()
  address: string

  @Field()
  description: string

  @Field(() => Coordinates)
  coordinates?: Coordinates
}

@Resolver()
export class FridgeResolver {
  @Mutation(() => Fridge)
  async createFridge (
    @Arg("inputs") inputs: FridgeInput,
    @Ctx() { req } : MyContext
  ): Promise<Fridge | undefined> {
      const author = Users.findOne({_id: req.session.userId});
      const {name, address, description, coordinates} = inputs;
  
      const fridge = new Fridges({
        name,
        address,
        description,
        author,
        coordinates: coordinates ? coordinates : undefined
      })
  
      try {
        await fridge.save()
      } catch (error) {
        console.log(error)
        return undefined
      } 
    
      return fridge
  }
}

我正在尝试引用 Fridges 类中的其他类,但不确定我是否做得对,但我无法想象这将是问题的根源。代码在这里:

import { Field, ID, ObjectType } from "type-graphql";
import { prop, getModelForClass, Ref } from "@typegoose/typegoose";
import { User } from './User';

export class Coordinates {
  lat: number
  lng: number
}

@ObjectType()
export class Fridge {
  @Field(() => ID, {nullable: true})
  _id: string

  @Field() 
  @prop({required: true})
  name: string;

  @Field() 
  @prop({required: true})
  address: string;

  @Field() 
  @prop({required: true})
  description: string;

  @Field(() => User, {nullable: true}) 
  @prop({required: true, ref: User})
  public author: Ref<User>

  @Field(() => Coordinates, {nullable: true}) 
  @prop({required: true})
  cordinates?: Coordinates;
};

export const Fridges = getModelForClass(Fridge);

最后是我的服务器的代码:

***** 一旦我移除 FridgeResolver,错误就会消失。此外,如果我删除了 FridgeResolver 中的所有代码,但将其留在 ApolloServer 中,它也会消失。********

import { ApolloServer } from "apollo-server-express";
import "colors";
import connectRedis from "connect-redis";
import cors from 'cors';
import express from "express";
import session from "express-session";
import Redis from "ioredis";
import mongoose from "mongoose";
import "reflect-metadata";
import { buildSchema } from "type-graphql";
import { COOKIE_NAME, __prod__ } from "./constants";
import { FridgeResolver } from './resolvers/fridge';
import { HelloResolver } from "./resolvers/hello";
import { UserResolver } from "./resolvers/user";

// create express instance:
const app = express();
// connect to our mongo database
const connectDB = async() => {
  try {
    const conn = await mongoose.connect('mongodb://localhost:27017/cff', {
      useNewUrlParser: true,
      useCreateIndex: true,
      useUnifiedTopology: true,
      useFindAndModify: false,
      autoIndex: true
    });
    console.log(`Mongo Connected to: ${conn.connection.host}`.cyan.bold)
  } catch (error) {
    console.log(`Error: ${error}`.red.bold);
    process.exit();
  }
};

connectDB();
const main = async () => {
  // Redis 
  const RedisStore = connectRedis(session);
  const redis = new Redis();
  // cors 
  app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true,
  }));
  // Session middleware needs to come before apollo so we can use it inside apollo middleware
  app.use(
    session({
      name: COOKIE_NAME,
      store: new RedisStore({
        client: redis, 
        disableTouch: true,
      }),
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 365 * 10, // 10 years
        httpOnly: true,
        sameSite: 'lax',
        secure: __prod__, // cookie only works in https 
      },
      secret: '123',
      resave: false,
      saveUninitialized: false,
    })
  );

  // Apollo server
  const apolloServer = new ApolloServer({
    schema: await buildSchema({
      resolvers: [HelloResolver, UserResolver, FridgeResolver],
      validate: false,
    }),
    context: ({ req, res }) => ({ req, res, redis })
  })
  apolloServer.applyMiddleware({ app, cors: false });
  const PORT = 4000;
  app.listen(PORT, ()=> {
    console.log(`Server is listening on port ${PORT}`.blue.bold)
  });
};

main().catch((err) => {
  console.log(err.red.bold)
});
4

2 回答 2

0

通过将冰箱类中的字段更改为:

import { Field, Float, ID, ObjectType } from "type-graphql";
import { prop, getModelForClass, Ref } from "@typegoose/typegoose";
import { User } from './User';

@ObjectType()
export class Fridge {
  @Field(() => ID, {nullable: true})
  _id: string

  @Field(() => String) 
  @prop({required: true})
  name: string;

  @Field(() => String) 
  @prop({required: true})
  address: string;

  @Field(() => String) 
  @prop({required: true})
  description: string;

  @Field(() => User) 
  @prop({ ref: () => User})
  public author: Ref<User>

  @Field(() => Float, {nullable: true}) 
  @prop()
  lat?: number

  @Field(() => Float, {nullable: true}) 
  @prop()
  lng?: number
};

export const Fridges = getModelForClass(Fridge);

我不完全理解这将如何导致未处理的承诺拒绝。如果有人有任何信息,将不胜感激,因为我自己无法找到任何东西。

于 2021-04-01T16:56:47.683 回答
0
    @Resolver()
export class FridgeResolver {
  @Mutation(() => Fridge)
  async createFridge (
    @Arg("inputs") inputs: FridgeInput,
    @Ctx() { req } : MyContext
  ): Promise<Fridge | undefined> {
      const author = await Users.findOne({_id: req.session.userId}); //You are using async function so you might have to use await here.
      const {name, address, description, coordinates} = inputs;
  
      const fridge = new Fridges({
        name,
        address,
        description,
        author,
        coordinates: coordinates ? coordinates : undefined
      })
  
      try {
        await fridge.save()
      } catch (error) {
        console.log(error)
        return undefined
      } 
    
      return fridge
  }
}
于 2021-04-01T03:44:57.050 回答