首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用nexus-prisma进行嵌套突变解析器

如何使用nexus-prisma进行嵌套突变解析器
EN

Stack Overflow用户
提问于 2019-04-24 14:58:00
回答 1查看 2.1K关注 0票数 4

我有以下数据模型:

代码语言:javascript
复制
type Job { 
    // ...
    example: String
    selections: [Selection!]
    // ...
}

type Selection { 
    ...
    question: String
    ...
}

我这样定义我的对象类型:

代码语言:javascript
复制
export const Job = prismaObjectType({
  name: 'Job',
  definition(t) {
    t.prismaFields([
      // ...
      'example',
      {
        name: 'selections',
      },
      // ...
    ])
  },
})

我这样做我的解析器:

代码语言:javascript
复制
t.field('createJob', {
  type: 'Job',
  args: {
    // ...
    example: stringArg(),
    selections: stringArg(),
    // ...
  },
  resolve: (parent, {
    example,
    selections
  }, ctx) => {
    // The resolver where I do a ctx.prisma.createJob and connect/create with example
  },
})

因此,现在在解析器中,我可以接收json字符串形式的选择,然后对其进行解析并使用作业进行连接/创建。

突变将如下所示:

代码语言:javascript
复制
mutation {
  createJob(
    example: "bla"
    selections: "ESCAPED JSON HERE"
  ){
    id
  }
}

我想知道有没有更优雅的,我可以这样做的:

代码语言:javascript
复制
mutation {
  createJob(
    example: "bla"
    selections: {
       question: "bla"
    }
  ){
    id
  }
}

代码语言:javascript
复制
mutation {
  createJob(
    example: "bla"
    selections(data: {
      // ...
    })
  ){
    id
  }
}

我注意到,使用nexus-prisma可以执行stringArg({list: true}),但不能真正执行对象。

我的主要问题是什么是做嵌套突变或连接在一起的最优雅的方式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-29 08:09:33

您可以使用文档中所示的inputObjectType

代码语言:javascript
复制
export const SomeFieldInput = inputObjectType({
  name: "SomeFieldInput",
  definition(t) {
    t.string("name", { required: true });
    t.int("priority");
  },
});

确保将类型作为传递给makeSchematypes的一部分包含在内。然后您可以使用它来定义参数,例如

代码语言:javascript
复制
args: {
  input: arg({
    type: "SomeFieldInput", // name should match the name you provided
  }),
}

现在,参数值将作为常规JavaScript对象而不是字符串提供给解析器。如果您需要输入对象的列表,或者希望使参数成为必需的,那么可以使用在使用标量时提供的same options来实现-- listnullabledescription等。

下面是一个完整的示例:

代码语言:javascript
复制
const Query = queryType({
  definition(t) {
    t.field('someField', {
      type: 'String',
      nullable: true,
      args: {
        input: arg({
          type: "SomeFieldInput", // name should match the name you provided
        }),
      },
      resolve: (parent, { input }) => {
        return `You entered: ${input && input.name}`
      },
    })
  },
})

const SomeFieldInput = inputObjectType({
  name: "SomeFieldInput",
  definition(t) {
    t.string("name", { required: true });
  },
});

const schema = makeSchema({
  types: {Query, SomeFieldInput},
  outputs: {
    ...
  },
});

然后按如下方式查询:

代码语言:javascript
复制
query {
  someField(
    input: {
       name: "Foo"
    }
  )
}

或者使用变量:

代码语言:javascript
复制
query($input: SomeFieldInput) {
  someField(input: $input)
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55824050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档