How to use the graphql.GraphQLError function in graphql

To help you get started, we’ve selected a few graphql examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aerogear / datasync / examples / restapi / server.js View on Github external
// gets JSON response from the external API, parameter `brand` is passed to the external API
      try {
        const response = await axios.get(
          `https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/${
            args.brand
          }`,
          {
            responseType: 'json',
            params: { format: 'json' }
          }
        )
        const { data } = response
        return data.Results
      } catch (e) {
        // do some error handling if necessary here
        throw new GraphQLError('Some error occured while calling the external API.')
      }
    }
  }
github APIs-guru / graphql-faker / src / proxy.ts View on Github external
function proxyResponse(response, args) {
  const rootValue = response.data || {};
  const globalErrors = [];

  for (const error of (response.errors || [])) {
    const { message, path, extensions } = error;
    const errorObj = new GraphQLError(
      message,
      undefined,
      undefined,
      undefined,
      path,
      undefined,
      extensions,
    );

    if (!path) {
      globalErrors.push(errorObj);
      continue;
    }

    // Recreate root value up to a place where original error was thrown
    // and place error as field value.
github HackGT / checkin2 / server / graphql.ts View on Github external
// Return none if the tag already exists (prevent duplicates)
                if (await Tag.findOne({name: args.tag})) {
                    return null;
                }

                let tag = new Tag({name: args.tag});
                if (args.start) tag.start = new Date(args.start);
                if (args.end) tag.end = new Date(args.end);
                if (tag.start && tag.end && tag.start >= tag.end) {
                    throw new GraphQLError("Invalid dates: the tag's end date must be after its start date");
                }
                if (!tag.start && tag.end) {
                    throw new GraphQLError("If a tag has an end date defined, it must also have a start date defined");
                }
                if (tag.start && !tag.end) {
                    throw new GraphQLError("If a tag has a start date defined, it must also have an end date defined");
                }
                tag.warnOnDuplicates = args.warnOnDuplicates;
                await tag.save();

                return {
                    name: args.tag,
                    start: args.start ? args.start : "",
                    end: args.end ? args.end : "",
                    warnOnDuplicates: args.warnOnDuplicates
                };
            }
        },
github apollographql / apollo-client / packages / apollo-client / src / core / __tests__ / QueryManager / index.ts View on Github external
it('runs a mutation with default errorPolicy equal to "none"', () => {
    const errors = [new GraphQLError('foo')];

    return mockMutation({
      mutation: gql`
        mutation makeListPrivate {
          makeListPrivate(id: "5")
        }
      `,
      errors,
    }).then(
      result => {
        throw new Error(
          'Mutation should not be successful with default errorPolicy',
        );
      },
      error => {
        expect(error.graphQLErrors).toEqual(errors);
github nethruster / nethloader-backend / src / graphql / resolvers / user.js View on Github external
if (user === null) throw new GraphQLError('User not found')
      } else {
        throw new GraphQLError('Unauthorized')
      }

      if ((currentUser.isAdmin && currentUser.id !== user.id) || await bcrypt.compare(args.oldPassword, user.password)) {
        return user.updateAttributes({
          password: await bcrypt.hash(args.newPassword, 12),
          sessionSignature: db.User.generateSessionSignature()
        })
          .catch(err => {
            console.error(err)
            throw new GraphQLError('Error while processing')
          })
      } else {
        throw new GraphQLError('Incorrect password')
      }
    },
    changeUserIsAdmin: async (parent, args, { currentUser }) => {
github aws-amplify / amplify-cli / packages / amplify-graphql-types-generator / src / utilities / graphql.ts View on Github external
export function getOperationRootType(schema: GraphQLSchema, operation: OperationDefinitionNode) {
  switch (operation.operation) {
    case 'query':
      return schema.getQueryType();
    case 'mutation':
      const mutationType = schema.getMutationType();
      if (!mutationType) {
        throw new GraphQLError('Schema is not configured for mutations', [operation]);
      }
      return mutationType;
    case 'subscription':
      const subscriptionType = schema.getSubscriptionType();
      if (!subscriptionType) {
        throw new GraphQLError('Schema is not configured for subscriptions', [operation]);
      }
      return subscriptionType;
    default:
      throw new GraphQLError('Can only compile queries, mutations and subscriptions', [operation]);
  }
}
github smartGraphQL / PROgraphQL / src / costRule / indexCost.js View on Github external
const costLimit = (rule: costComplexityOptions): Function => {
  if (rule.costLimit <= 0) throw new GraphQLError('Cost limit must be greater than 0');

  return (context: ValidationContext): CostComplexityOptions => {
    return new CostComplexityOptions((context: ValidationContext), (rule: costComplexityOptions));
  };
};
github alexvcasillas / react-forum-system / backend / src / graphql / mutations / authenticate.mutation.js View on Github external
resolve: async (root, { email, password }, ctx) => {
    const { db, auth } = ctx;
    if (email === '' || password === '') return MISSING_PARAMETERS;
    const user = await db.user.findOne({ email });
    if (!user) return NOT_FOUND;
    const equalPasswords = await user.comparePassword(password);
    if (!equalPasswords) return new GraphQLError(Response({ status: 400, message: 'Bad Request' }));
    let authToken;
    try {
      authToken = await auth.generateToken({ identifier: user._id, email: user.email });
    } catch (error) {
      return new GraphQLError(
        Response({
          status: 500,
          message: `An error ocurred while generating the authentication token for the user.`,
        }),
      );
    }
    ctx.response.cookie('token', authToken, {
      httpOnly: true,
      domain: config.cookieDomain,
      maxAge: 1000 * 60 * 60 * 24 * 365,
    });
github apollographql / apollo-server / packages / apollo-server-core / src / ApolloServer.ts View on Github external
Field(node: FieldDefinitionNode) {
    if (node.name.value === '__schema' || node.name.value === '__type') {
      context.reportError(
        new GraphQLError(
          'GraphQL introspection is not allowed by Apollo Server, but the query contained __schema or __type. To enable introspection, pass introspection: true to ApolloServer in production',
          [node],
        ),
      );
    }
  },
});
github im6 / vp / src / server / middlewares / graphql / root.js View on Github external
const username = hasUserSignIn ? sessionUsername : null;
    const userId = hasUserSignIn ? sessionUserid : null;

    const random = (Math.random() * 10).toFixed();
    if (color.length === 27) {
      try {
        const row = await sqlExecOne(
          'INSERT INTO colorpk_color (`like`, color, userid, username, colortype, display, createdate) VALUES (?, ?, ?, ?, NULL, ?, NOW())',
          [random, color, userId, username, hasUserSignIn ? 0 : 1]
        );
        return {
          status: 0,
          data: row.insertId,
        };
      } catch (err) {
        return new GraphQLError(err.toString());
      }
    } else {
      return new GraphQLError('create error: invalid color input');
    }
  },