Why server no restarting after error in validation

26 Views Asked by At

I am working with node.js and Graphql without Express, to validate the input i use Joi, so in my mutation resolver i did this:

 async user(_, { input }, { dataSources }) {
    if (process.env.NODE_ENV === 'development') {
      debug(input);
    }

    // Validation
    if (input.role === 'user') {
      debug('validate user creation schema');
      validate(userSchemas.userRegisterSchema.post, input);
    } else if (input.role === 'pro') {
      debug('validate pro creation schema');
      validate(userSchemas.userProRegisterSchema);
    } else {
      throw new Error('Bad input error');
    }

so this is the code in the validate function folder:

import Debug from 'debug';
import BadInputError from '../errors/BadInputError.js';
/*
* validate module.
* @module validate
*/
const debug = Debug(`${process.env.DEBUG_MODULE}:validation`);

// function to validate the input data
async function validate(schema, inputData) {
  try {
    debug('validate input data');
    await schema.validateAsync(inputData);
  } catch (error) {
    debug('validation error');
    throw new BadInputError(error);
  }
}

export default validate;

And when entry is wrong i have the error but server crash, i don't want server crash... Have you an idea please? thank you

i try a lot of things, with return and some idea of IA but nothing good.

2

There are 2 best solutions below

4
Atique On

You don't need to throw error from else condition.

throw new Error('Bad input error');

this error do not have any handling when the promise is rejected. you can also use unhandledRejection event at process level if required. https://nodejs.org/api/process.html#event-unhandledrejection

or else just log using your logger.

'Bad input error'
0
xtreme66 On

I found an other solution to validate with custom scalar,I found it complicated but through reflection I managed to implement it, which allows me to validate directly in the schemas, this the code :

import { GraphQLScalarType, GraphQLError } from 'graphql';
import validator from 'validator';

const validateEmail = new GraphQLScalarType({
  name: 'Email',
  description: 'Email custom scalar type',
  serialize(value) {
    // Validation during serialization
    if (!validator.isEmail(value)) {
      throw new GraphQLError('Invalid email address');
    }
    return value;
  },
  parseValue(value) {
    // Validation during value analysis
    if (!validator.isEmail(value)) {
      throw new GraphQLError('Invalid email address');
    }
    return value;
  },
  parseLiteral(ast) {
    // Validation during AST analysis
    if (!validator.isEmail(ast.value)) {
      throw new GraphQLError('Invalid email address');
    }
    return ast.value;
  },
});

const validatePassword = new GraphQLScalarType({
  // minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1,
  // minSymbols: 1, returnScore: false, pointsPerUnique: 1,
  // pointsPerRepeat: 0.5, pointsForContainingLower: 10,
  // pointsForContainingUpper: 10, pointsForContainingNumber: 10,
  //  pointsForContainingSymbol: 10 }
  name: 'Password',
  description: 'Password custom scalar type',
  serialize(value) {
    // Validation during serialization
    if (!validator.isStrongPassword(value)) {
      throw new GraphQLError('Invalid password');
    }
    return value;
  },
  parseValue(value) {
    // Validation during value analysis
    if (!validator.isStrongPassword(value)) {
      throw new GraphQLError('Invalid password');
    }
    return value;
  },
  parseLiteral(ast) {
    // Validation during AST analysis
    if (!validator.isStrongPassword(ast.value)) {
      throw new GraphQLError('Invalid password');
    }
    return ast.value;
  },
});

export { validateEmail, validatePassword };

import on index.js fromresolvers:

import { validateEmail, validatePassword } from '../validations/scalars.js';

export default {
  validateEmail,
  validatePassword,
  Query,
 };

and import in index.js on schemas:

const schema = `#graphql
scalar validateEmail
scalar validatePassword
    ${Query}
    ${Mutation}
`;

export default schema;