【问题标题】:Directives on scalars in Apollo GraphQL ServerApollo GraphQL Server 中的标量指令
【发布时间】:2021-01-10 21:46:05
【问题描述】:

我的架构中有一个日期定义为标量。

有没有办法只在一个地方定义有关法律价值的规则?

我可能会在 FIELD_DEFINITION 上定义一个指令并将其应用于此类型的每个字段。但是,我想这样做一次。这可能吗?

这是我的代码。 CitizenshipCode实际上是一个字符串,仅限于“us”、“uk”、“de”等值。我想以集中的方式实现验证,而不是为这种类型的每个字段添加指令:

scalar CitizenshipCode    # is it possible to implement the validation here?


type Client {
  id: ID!
  name: String
  citizenship: CitizenshipCode   #  instead of here...
  # other atts
}

type User {
  id: ID!
  email: String
  citizenship: CitizenshipCode   #  ... and here
  # other atts
}

【问题讨论】:

  • 可以在定义标量的地方添加一段代码吗?另外,“关于值的规则”是什么意思,是关于验证吗?
  • 谢谢@Anastasiia!我更新了我的描述文本来回答这个问题。

标签: node.js graphql apollo-server


【解决方案1】:

您可以在代码中使用枚举类型或自定义架构:

const { ApolloServer, gql, SchemaDirectiveVisitor } = require('apollo-server');
const { GraphQLScalarType, Kind } = require('graphql');

const validCountryCodes = [ "US", "UK", "DE"];

const citizenshipCodeScalar = new GraphQLScalarType({
    name: 'CitizenshipCode',
    description: 'Allowed citizen ship codes',
    serialize(value) {
        return validCountryCodes.includes(value) ? value : "INVALID COUNTRY";
    },
    parseValue(value) {
        return validCountryCodes.includes(value) ? value : null;
    },
    parseLiteral(ast) {
        return ast.kind === Kind.STRING ? ast.value : null;
    }
});

const typeDefs = gql `
  scalar CitizenshipCode

  type Client {
    id: ID
    name: String
    citizenship: CitizenshipCode
  }

  type User {
    id: Int
    email: String
    citizenship: CitizenshipCode
  }

  type Query {
      clients: [Client]
      users: [User]
  }
`;

const resolvers = {
    Query: {
        clients: () => clients,
        users: () => users
    },
    CitizenshipCode: citizenshipCodeScalar
};

const client = [{
        id: 'client1',
        name: 'The Awakening',
        citizenship: 'US'
    },
    {
        id: 'client2',
        title: 'City of Glass',
        citizenship: 'CA',
    },
];

const users = [{
        id: 1,
        email: 'test1@test.com',
        citizenship: 'UK',
    },
    {
        id: 2,
        email: 'test2@test.com',
        citizenship: 'DE',
    },
];

const server = new ApolloServer({
    typeDefs,
    resolvers
});

【讨论】:

  • @Aleks 你有机会看看吗?
  • @Aleks 奇怪!似乎为我工作。这是我的节点应用代码,看一下:pastebin.com/ScZMAuRS
  • 谢谢,它成功了,这正是我所需要的。
猜你喜欢
  • 2019-11-16
  • 2017-05-24
  • 2019-09-29
  • 2019-09-01
  • 2019-07-26
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
相关资源
最近更新 更多