我正在通过GraphQL-Js和Mongo学习GraphQL。
我发现GraphQL模式有很多代码重复。
我的GraphQL输入对象看起来像这样:
const PricingInputType = new GraphQLInputObjectType({
name: 'PricingInput',
fields: () => ({
expires: { type: GraphQLInt },
private: { type: GraphQLBoolean },
monthly: { type: GraphQLInt },
scanEnvelope: { type: GraphQLInt },
initalScan: { type: GraphQLInt },
perPage: { type: GraphQLInt },
forwardMail: { type: GraphQLInt },
forwardParcel: { type: GraphQLInt },
shred: { type: GraphQLInt },
perMonthPerGram: { type: GraphQLInt },
freeStorePerGram: { type: GraphQLInt },
setup: { type: GraphQLInt },
idFree: { type: GraphQLInt }
})
});
const PlanInputType = new GraphQLInputObjectType({
name: 'PlanInput',
fields: () => ({
id: { type: GraphQLString },
planName: { type: GraphQLString },
pricing: { type: PricingInputType }
})
});
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addPlan: {
type: PlanType,
args: {
Plan: { type: PlanInputType }
},
resolve(parent, args){
//TO DO. UPSERT TO MONGO
return true;
}
}
}
});
我的查询对象如下:
const PricingType = new GraphQLObjectType({
name: "Pricing",
fields: () => ({
expires: { type: GraphQLInt },
private: { type: GraphQLBoolean },
monthly: { type: GraphQLInt },
scanEnvelope: { type: GraphQLInt },
initalScan: { type: GraphQLInt },
perPage: { type: GraphQLInt },
forwardMail: { type: GraphQLInt },
forwardParcel: { type: GraphQLInt },
shred: { type: GraphQLInt },
perMonthPerGram: { type: GraphQLInt },
freeStorePerGram: { type: GraphQLInt },
setup: { type: GraphQLInt },
idFree: { type: GraphQLInt }
})
});
const PlanType = new GraphQLObjectType({
name: "Plan",
fields: () => ({
id: { type: GraphQLString },
planName: { type: GraphQLString },
pricing: { type: PricingType }
})
});
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
plans: {
type: new GraphQLList(PlanType),
resolve(parent, args) {
return Plans.find({});
}
}
}
});
现在我的Mongo模式如下:
var plansSchema = new Schema({
planName: {
type: String,
required: [true, "Plan name is required"]
},
pricing: {
monthly: Number,
scanEnvelope: Number,
initalScan: Number,
perPage: Number,
forwardMail: Number,
forwardParcel: Number,
shred: Number,
perMonthPerGram: Number,
freeStorePerGram: Number,
setup: Number,
idFree: Number
},
expires: Number,
private: Boolean,
deleted: Boolean,
date: { type: Date, default: Date.now },
});
module.exports = mongoose.model('plans', plansSchema);
如您所见,我正在3个地方复制代码。如果我决定按季度而不是按月收费,则需要在3个地方更改“每月”属性!?
是否有更好的模式?还是这只是这样做的方法?