How to use the apollo-server.UserInputError function in apollo-server

To help you get started, we’ve selected a few apollo-server 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 borisowsky / nodejs-graphql-guide / src / graphql / resolvers / userCreate.mutation.ts View on Github external
// Input validation
  const errors = await validate(user);

  if (errors.length > 0) {
    throw new UserInputError('Validation failed!', {
      fields: formatClassValidatorErrors(errors),
    });
  }

  const [searchByEmail, searchByUsername] = await Promise.all([
    User.find({ email: args.input.username }),
    User.find({ username: args.input.username }),
  ]);

  if (searchByEmail.length > 0) {
    throw new UserInputError('Validation failed!', {
      fields: {
        email: ['User with such E-Mail already exists'],
      },
    });
  }

  if (searchByUsername.length > 0) {
    throw new UserInputError('Validation failed!', {
      fields: {
        username: ['User with such username already exists'],
      },
    });
  }

  return await user.save();
};
github Human-Connection / Human-Connection / backend / src / middleware / nodes / locations.js View on Github external
throw new UserInputError('locationName is invalid')
  }

  let data

  res.features.forEach(item => {
    if (item.matching_place_name === locationName) {
      data = item
    }
  })
  if (!data) {
    data = res.features[0]
  }

  if (!data || !data.place_type || !data.place_type.length) {
    throw new UserInputError('locationName is invalid')
  }

  const session = driver.session()
  if (data.place_type.length > 1) {
    data.id = 'region.' + data.id.split('.')[1]
  }
  await createLocation(session, data)

  let parent = data

  if (data.context) {
    await asyncForEach(data.context, async ctx => {
      await createLocation(session, ctx)
      try {
        await session.writeTransaction(transaction => {
          return transaction.run(
github Human-Connection / Human-Connection / backend / src / schema / resolvers / registration.js View on Github external
)
      const emailAddress = await neode.hydrateFirst(result, 'email', neode.model('EmailAddress'))
      if (!emailAddress) throw new UserInputError('Invalid email or nonce')
      args = await fileUpload(args, { file: 'avatarUpload', url: 'avatar' })
      args = await encryptPassword(args)
      try {
        const user = await neode.create('User', args)
        await Promise.all([
          user.relateTo(emailAddress, 'primaryEmail'),
          emailAddress.relateTo(user, 'belongsTo'),
          emailAddress.update({ verifiedAt: new Date().toISOString() }),
        ])
        return user.toJson()
      } catch (e) {
        if (e.code === 'Neo.ClientError.Schema.ConstraintValidationFailed')
          throw new UserInputError('User with this slug already exists!')
        throw new UserInputError(e.message)
      }
    },
  },
github the-road-to-graphql / fullstack-apollo-express-mongodb-boilerplate / src / resolvers / user.js View on Github external
signIn: async (
      parent,
      { login, password },
      { models, secret },
    ) => {
      const user = await models.User.findByLogin(login);

      if (!user) {
        throw new UserInputError(
          'No user found with this login credentials.',
        );
      }

      const isValid = await user.validatePassword(password);

      if (!isValid) {
        throw new AuthenticationError('Invalid password.');
      }

      return { token: createToken(user, secret, '30m') };
    },
github Human-Connection / Human-Connection / backend / src / schema / resolvers / registration.js View on Github external
Signup: async (_parent, args, context) => {
      args.nonce = generateNonce()
      args.email = normalizeEmail(args.email)
      let emailAddress = await existingEmailAddress({ args, context })
      if (emailAddress) return emailAddress
      try {
        emailAddress = await neode.create('EmailAddress', args)
        return emailAddress.toJson()
      } catch (e) {
        throw new UserInputError(e.message)
      }
    },
    SignupVerification: async (_parent, args) => {
github Human-Connection / Human-Connection / backend / src / middleware / validation / validationMiddleware.js View on Github external
const validatePost = async (resolve, root, args, context, info) => {
  const { categoryIds } = args
  if (!Array.isArray(categoryIds) || !categoryIds.length || categoryIds.length > 3) {
    throw new UserInputError(NO_CATEGORIES_ERR_MESSAGE)
  }
  return resolve(root, args, context, info)
}
github eddeee888 / base-react-app / graphql / src / graphql / resolvers / Mutation / signup / signup.ts View on Github external
const validateInput = async (
  { prisma }: ResolverContext,
  input: SignupInput
): Promise => {
  const inputErrors = await validateSignupInput(input);
  if (inputErrors) {
    throw new UserInputError('Invalid input', inputErrors);
  }

  const canBeCreated = await canUserBeCreated(prisma, input.email);
  if (!canBeCreated) {
    throw new UserInputError('Invalid input', {
      email: ['Email already exists']
    });
  }
};
github Human-Connection / Human-Connection / backend / src / schema / resolvers / registration.js View on Github external
throw new UserInputError('Invalid version format!')
      }
      args.termsAndConditionsAgreedAt = new Date().toISOString()

      let { nonce, email } = args
      email = normalizeEmail(email)
      const result = await neode.cypher(
        `
      MATCH(email:EmailAddress {nonce: {nonce}, email: {email}})
      WHERE NOT (email)-[:BELONGS_TO]->()
      RETURN email
      `,
        { nonce, email },
      )
      const emailAddress = await neode.hydrateFirst(result, 'email', neode.model('EmailAddress'))
      if (!emailAddress) throw new UserInputError('Invalid email or nonce')
      args = await fileUpload(args, { file: 'avatarUpload', url: 'avatar' })
      args = await encryptPassword(args)
      try {
        const user = await neode.create('User', args)
        await Promise.all([
          user.relateTo(emailAddress, 'primaryEmail'),
          emailAddress.relateTo(user, 'belongsTo'),
          emailAddress.update({ verifiedAt: new Date().toISOString() }),
        ])
        return user.toJson()
      } catch (e) {
        if (e.code === 'Neo.ClientError.Schema.ConstraintValidationFailed')
          throw new UserInputError('User with this slug already exists!')
        throw new UserInputError(e.message)
      }
    },
github jackrobertscott / forge / packages / server / src / resolvers / providerResolvers.ts View on Github external
password,
      }: { username: string; password: string; email: string }
    ) {
      const provider = await Provider.findOne({
        domain: 'custom',
        'payload.username': username,
      });
      if (!provider) {
        throw new UserInputError(
          `Could not find a login with the username "${username}".`
        );
      }
      const match = await comparePassword(password, provider.payload
        .password as string);
      if (!match) {
        throw new UserInputError('Password is incorrect.');
      }
      const user = await User.findById(provider.creatorId);
      if (!user) {
        throw new Error('User was not found.');
      }
      recordUser({
        userId: user.id,
        traits: user.toRecord(),
      });
      recordAction({
        userId: user.id,
        scope: 'Provider',
        action: 'Custom Logged In',
      });
      return {
        token: encode({ userId: user.id }),
github Human-Connection / Human-Connection / backend / src / schema / resolvers / posts.js View on Github external
WITH post
        UNWIND $categoryIds AS categoryId
        MATCH (category:Category {id: categoryId})
        MERGE (post)-[:CATEGORIZED]->(category)
        RETURN post`

      const createPostVariables = { userId: context.user.id, categoryIds, params }

      const session = context.driver.session()
      try {
        const transactionRes = await session.run(createPostCypher, createPostVariables)
        const posts = transactionRes.records.map(record => record.get('post').properties)
        return posts[0]
      } catch (e) {
        if (e.code === 'Neo.ClientError.Schema.ConstraintValidationFailed')
          throw new UserInputError('Post with this slug already exists!')
        throw new Error(e)
      } finally {
        session.close()
      }
    },
    UpdatePost: async (_parent, params, context, _resolveInfo) => {