【问题标题】:react server side validation反应服务器端验证
【发布时间】:2020-04-08 22:16:30
【问题描述】:

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

这是我的验证.ts。

/* 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 中正确编写它以获得结果。下面是如何在客户端编写查询,我在下面写了这个,它可以工作并尝试在这里工作,但它不起作用。如何编写一个简单的查询以从 validation.ts 中的 CHECK_EMAIL_QUERY 获得返回?

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

        return forgotPassword;
      }
    })
  })

这是客户端 graphql 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)
      }
    },

【问题讨论】:

    标签: reactjs apollo react-apollo


    【解决方案1】:

    在继续验证之前,您可能需要等待 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      相关资源
      最近更新 更多