Mon*_*key 22 graphql graphql-js
我有一些我想用作输入和输出的对象类型 - 例如货币类型或预订类型.
如何定义我的模式以使其具有支持输入和输出的类型 - 如果我不需要,我不想重复代码.我也不想创建重复的输入类型的东西,如货币和状态枚举.
export const ReservationInputType = new InputObjectType({
name: 'Reservation',
fields: {
hotelId: { type: IntType },
rooms: { type: new List(RoomType) },
totalCost: { type: new NonNull(CurrencyType) },
status: { type: new NonNull(ReservationStatusType) },
},
});
export const ReservationType = new ObjectType({
name: 'Reservation',
fields: {
hotelId: { type: IntType },
rooms: { type: new List(RoomType) },
totalCost: { type: new NonNull(CurrencyType) },
status: { type: new NonNull(ReservationStatusType) },
},
});
Run Code Online (Sandbox Code Playgroud)
Com*_*are 17
在GraphQL规范中,对象和输入对象是不同的东西.引用输入对象的规范:
字段可以定义客户端使用查询传递的参数,以配置其行为.这些输入可以是字符串或枚举,但它们有时需要比这更复杂.
对象类型...不适合在此处重复使用,因为对象可以包含表示循环引用或对接口和联合的引用的字段,这两个字段都不适合用作输入参数.因此,输入对象在系统中具有单独的类型.
输入对象定义一组输入字段; 输入字段是标量,枚举或其他输入对象.这允许参数接受任意复杂的结构.
虽然实现可能提供便利代码来从单个定义创建对象和相应的输入对象,但是在规则下,规范表明它们必须是单独的东西(具有单独的名称,例如Reservation和ReservationInput).
你可以这样做:
export const createTypes = ({name, fields}) => {
return {
inputType: new InputObjectType({name: `${name}InputType`, fields}),
objectType: new ObjectType({name: `${name}ObjectType`, fields})
};
};
const reservation = createTypes({
name: "Reservation",
fields: () => ({
hotelId: { type: IntType },
rooms: { type: new List(RoomType) },
totalCost: { type: new NonNull(CurrencyType) },
status: { type: new NonNull(ReservationStatusType) }
})
});
// now you can use:
// reservation.inputType
// reservation.objectTypeRun Code Online (Sandbox Code Playgroud)
在处理一个项目时,我在input和type对象之间遇到了类似的代码重复问题。我没有发现该extend关键字很有帮助,因为它仅扩展了该特定类型的字段。所以type对象中的字段不能在input对象中继承。
最后,我发现这种使用文字表达式的模式很有帮助:
const UserType = `
name: String!,
surname: String!
`;
const schema = graphql.buildSchema(`
type User {
${UserType}
}
input InputUser {
${UserType}
}
`)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6753 次 |
| 最近记录: |