簡體   English   中英

如何將函數中的值插入到 graphql 突變中?

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

我正在編寫一個解析器,它將從 json 對象數組中獲取所有文件並將其插入到 db.have 3 個字段中的 schema , userid ,在名為 getallmessages 的函數中返回的文本。 我正在嘗試使用 graphql 解析器將這 3 個值插入到消息表中。 但是,我收到一條錯誤消息,說Cannot read property 'getallmessages' of undefined {"name":"GraphQLError"}

這是我的突變

  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 函數,返回用戶 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;
}

消息模型

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;
  }
}

消息.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!
}

您應該將ChatService添加到解析器的context中,它是第三個參數,而不是第四個參數。 查看根字段和解析器

context提供給每個解析器並保存重要上下文信息的值,例如當前登錄的用戶或對數據庫的訪問。

暫無
暫無

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

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