反应服务器端验证

时间:2019-12-16 12:38:49

标签: reactjs apollo react-apollo

我的应用程序基于apollo-universal-starter套件(反应客户端,节点服务器)构建。有一个执行客户端验证的用户验证模块。这与其他模块的编写方式不同。它进行客户端验证,但是我正尝试通过服务器端验证来检查电子邮件是否存在于数据库中。我无法正确编写graphql查询来获取结果。我尝试使其类似于其他模块中的查询,但是它不起作用。

这是我的验证。

/* tslint:disable: variable-name */
import i18n from 'i18next';
import { graphql } from 'react-apollo';
import CHECK_EMAIL_QUERY from '@gqlapp/user-client-react/graphql/CheckEmail.graphql';
import { translate } from '@gqlapp/i18n-client-react';


export const emailCheck = (email) => {
  var checkEmail = undefined;
  let result = graphql(CHECK_EMAIL_QUERY, variables: { input: { email } },   data: { checkEmail })
  console.log(result)
}

/**
 * Validates if the value is empty.
 *
 * @param value
 * @return {undefined | string}
 */
export const required = (value: any) => (value ? undefined : i18n.t('validation:required'));

/**
 * Validates if the value matches a particular value.
 * @param comparableField
 */
export const match = (comparableField: string) => (value: any, values: any) =>
  value !== values[comparableField] ? i18n.t('validation:match', { comparableField }) : undefined;

/**
 * Validates the maximal length of the value.
 * Usage: const maxLength15 = maxLength(15)
 *
 * @param max
 * @return {undefined | string}
 */
export const maxLength = (max: number) => (value: any) =>
  value && value.length > max ? i18n.t('validation:maxLength', { max }) : undefined;

/**
 * Validates the minimal length of the value.
 * Usage: export const minLength2 = minLength(2)
 *
 * @param min
 * @return {undefined | string}
 */
export const minLength = (min: number) => (value: any) =>
  value && value.length < min ? i18n.t('validation:minLength', { min }) : undefined;

/**
 * Validates if the value is a number.
 *
 * @param value
 * @return {undefined | string}
 */
export const number = (value: any) => (value && isNaN(Number(value)) ? i18n.t('validation:number') : undefined);

/**
 * Validates if the value is a string.
 *
 * @param value
 * @return {undefined | string}
 */
export const string = (value: any) =>
  value && !(typeof value === 'string' || value instanceof String) ? i18n.t('validation:string') : undefined;

/**
 * Validates the minimal value.
 * Usage: export const minValue18 = minValue(18);
 *
 * @param min
 * @return {undefined | string}
 */
export const minValue = (min: number) => (value: any) =>
  value && value < min ? i18n.t('validation:minValue', { min }) : undefined;

/**
 * Validates the email.
 *
 * @param value
 * @return {undefined | string}
 */
export const email = (value: any) => {
  //const result =  graphql.query({ query: CHECK_EMAIL_QUERY, variables: { email: 'canercak@gmail.com' } })
  //console.log(result)
  emailCheck('canercak@gmail.com')
  return  value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) ? i18n.t('validation:email') : undefined;
}




/**
 * Validates if the value is alpha-numeric.
 *
 * @param value
 * @return {undefined | string}
 */
export const alphaNumeric = (value: any) =>
  value && /[^a-zA-Z0-9 ]/i.test(value) ? i18n.t('validation:alphaNumeric') : undefined;

/**
 * Validates the phone number.
 *
 * @param value
 * @return {undefined | string}
 */
export const phoneNumber = (value: any) =>
  value && !/^(\+)?([ 0-9]){10,16}$/i.test(value) ? i18n.t('validation:phoneNumber') : undefined;

/**
 * Schema interface for the validate function.
 */
export interface Schema {
  [key: string]: Array<(value: any, values: { [key: string]: any }) => string | undefined> | Schema;
}

/**
 * Validates the input object according to the input schema.
 *
 * @param object
 * @param schema
 * @return object with errors
 */
export const validate = (object: { [key: string]: any }, schema: Schema) => {
  const errors = {};
  const validateFormInner = (
    values: { [key: string]: any },
    innerSchema: Schema,
    collector: { [key: string]: string }
  ) => {
    Object.keys(innerSchema)
      .filter(v => innerSchema.hasOwnProperty(v))
      .forEach(v => {
        const s = innerSchema[v];

        if (Array.isArray(s)) {
          s.forEach(validator => {
            const result = validator(values[v], values);
            if (result) {
              collector[v] = result;
            }
          });
        } else {
          validateFormInner(values[v], innerSchema[v] as Schema, collector);
        }
      });

    return collector;
  };

  const collectedErrors = validateFormInner(object, schema, errors);
  return Object.keys(collectedErrors).length ? collectedErrors : undefined;
};

我首先在客户端调用“ email”,然后再调用“ emailCheck”。如果我在系统页面中按以下方式编写查询,则查询工作正常,但无法在valdiation.ts中正确编写查询以获取结果。下面是在客户端编写查询的方式,我在下面编写了此代码,它可以工作并尝试在此处工作,但不起作用。我该如何编写一个简单的查询以从validate.ts中的CHECK_EMAIL_QUERY获得退货?

 graphql(CHECK_EMAIL_QUERY, {
    props: ({ mutate }) => ({
      checkEmail: async ({ email }) => {
        const {
          data: { checkEmail }
        } = await mutate({
          variables: { input: { email } }
        });

        return forgotPassword;
      }
    })
  })

这是客户端图形ql CHECK_EMAIL_QUERY

    mutation checkEmail($input: CheckEmailInput!) {
      checkEmail(input: $input)
    }

这是服务器端解析器

  async checkEmail(obj, { input }, { User }) {
      try {
        const localAuth = pick(input, 'email');
        const user = await User.getUserByEmail(localAuth.email);
        if (user) {
          return user;
        } else {
          return null;
        }
      } catch (e) {
        console.log(e)
      }
    },

1 个答案:

答案 0 :(得分:0)

在继续验证之前,您可能需要等待promise的解决。

如果您的验证中间件支持promises,则类似以下的事情应该起作用:

export const emailCheck = async (email) => {
  let result = await graphql.query({ query: CHECK_EMAIL_QUERY, variables: { email } })
  return result != null
}

export const email = async (value: string) => {
  let emailExist = await emailCheck(value)
  return  emailExist && value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) ? i18n.t('validation:email') : undefined;
}