简体   繁体   English

如何将函数中的值插入到 graphql 突变中?

[英]how to insert values from function into graphql mutation?

im writing a resolver that will take all fileds from json array of objects and insert it into db.have 3 fields in schema , userid , text that are being returned in a function called getallmessages.我正在编写一个解析器,它将从 json 对象数组中获取所有文件并将其插入到 db.have 3 个字段中的 schema , userid ,在名为 getallmessages 的函数中返回的文本。 Im trying to insert those 3 values into message table using graphql resolver.我正在尝试使用 graphql 解析器将这 3 个值插入到消息表中。 However im getting an error saying Cannot read property 'getallmessages' of undefined {"name":"GraphQLError"}但是,我收到一条错误消息,说Cannot read property 'getallmessages' of undefined {"name":"GraphQLError"}

here is my mutation这是我的突变

  Mutation: {
    addMessage: async (
      _: any,
      { input }: any,
      { user }: any,
      { chatService }: any,
    ): Promise<any> => {
      console.log(input, user);
      console.log(chatService);

      const messages = await chatService.getallmessages(input.podId);

      const podmessage = await MessageModel.query()
       .insert({...messages }) // , userId: user.id })
       .returning('*');


      return podmessage;
   },
 },

getallmessages function that returns userid , text and message id getallmessages 函数,返回用户 ID、文本和消息 ID

  public async getallmessages(podId: string) {
const channel = ChatService.client.channel('messaging', podId);
const messageFilter = { id: { $exists: true } };
const response = await channel.search(messageFilter);
const result = response.results.map((message) => ({
id: message.message.id,
text: message.message.text,
userId: message.message.user?.id,

}));


return result;
}

messagemodel消息模型

import { BaseModel } from '@/db';

import { messageSchema } from './schema/message.schema';

export class MessageModel extends BaseModel {
  public static tableName = 'message';

  public id!: number;
  // public messageid!: number;
  public userId!: number;
  public text!: string;

  public static get jsonSchema() {
    return messageSchema;
  }
}

message.graphql消息.graphql

type Message {
  id: ID!
  text: String!
  userId: Int!
  createdAt: Timestamp!
}

input MessageInput {
  id: ID!
  text: String!
  userId: Int!
  podId: Int!
}


extend type Query {
  messages: [Message]!
  message(podId: ID!): Message!
}

extend type Mutation {
  addMessage(input: MessageInput!): Message!
  updateMessage(id: ID!, input: MessageInput!): Message!
}

You should add the ChatService into the context of a resolver, it's the third parameter, NOT the fourth.您应该将ChatService添加到解析器的context中,它是第三个参数,而不是第四个参数。 See Root fields & resolvers查看根字段和解析器

context A value which is provided to every resolver and holds important contextual information like the currently logged in user, or access to a database. context提供给每个解析器并保存重要上下文信息的值,例如当前登录的用户或对数据库的访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM