Преодоление дублирования кода с помощью схем Graphql-js - PullRequest
0 голосов
/ 02 декабря 2018

Я изучаю GraphQL с GraphQL-Js & Mongo.

Я обнаружил, что в 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({});
      }
    }
  }
});

Теперь моя схема Монго выглядит следующим образом:

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 местах!?

Есть ли лучший шаблон?или это просто способ сделать это?

1 Ответ

0 голосов
/ 22 января 2019

Можете посмотреть на мой ответ на аналогичный вопрос.Он использует пакет , который опирается на GraphQL «объект запроса» для генерации всего остального и, следовательно, воздерживается от mongoose от использования прямой MongoDB.

...