简体   繁体   English

将 Int 值传递给 GraphQL

[英]Pass Int Values to GraphQL

I am running a graphql query with these data types:我正在使用以下数据类型运行 graphql 查询:

mutation AddVehicle(
    $freeSeats: Number!
    $numberPlate: String!
    $userId: Number!
  )

On my front-end, I am using material ui text-fields, which take an input as a string by default.在我的前端,我使用材料 ui 文本字段,默认情况下将输入作为字符串。 To change it into integers, I used Number(freeSeats) etc while passing parameters into the submitForm function.要将其更改为整数,我在将参数传递到submitForm function 时使用了Number(freeSeats)等。

However, when I submit the form I still get these errors, which means that the values are still being passed as strings.但是,当我提交表单时,我仍然会收到这些错误,这意味着这些值仍然作为字符串传递。 How can I fix this?我怎样才能解决这个问题?

 The specified value type of field `freeSeats` does not match the field type.
GraphQL error: The specified value type of field `userId` does not match the field type.

I also tried to console.log(isNumber(freeSeats) in the beginning of the submitForm function. It prints true. So I know that the strings are being converted to integers but not being passed correctly in the mutation.我还尝试在submitForm function 的开头使用console.log(isNumber(freeSeats) 。它打印为 true。所以我知道字符串正在被转换为整数,但在突变中没有正确传递。

export default function AddVehiclePage() {
    const [isSubmitted, setIsSubmitted] = useState(false);
    const [isAdded, setIsAdded] = useState(false);
    const [errorMessage, setErrorMessage] = useState('');

    const [addVehicle] = useMutation(ADD_VEHICLE);

    const formik = useFormik({
        initialValues:{
            freeSeats: '',
            numberPlate: '',
            userId: '',
        },
        onSubmit:(values, actions) => {
          submitForm(Number(formik.values.freeSeats),formik.values.numberPlate,Number(formik.values.userId));           
           validationSchema:schema
        })

    let submitForm = (
        freeSeats: Number,
        numberPlate: string,
        userId: Number,
    ) => {
      setIsSubmitted(true);
      addVehicle({
        variables: {
          freeSeats: freeSeats,
          numberPlate: numberPlate,
          userId: userId,
        },
      })
        .then(({ data }: ExecutionResult<CreateVehicleResponse>) => {
          if (data !== null && data !== undefined) {
            setIsAdded(true);
          }
        })
        .catch((error: { message: string }) => {
          console.log('Error msg:' + error.message);
        });
    };

    return (
      <div>
                <Form
                  onSubmit={e => {
                    e.preventDefault();
                    formik.handleSubmit();
                  }}>
                  <div>
                    <TextField
                      variant="outlined"
                      margin="normal"
                      id="freeSeats"
                      name="freeSeats"
                      helperText={formik.touched.freeSeats ? formik.errors.freeSeats : ''}
                      error={formik.touched.freeSeats && Boolean(formik.errors.freeSeats)}
                      label="Free Seats"
                      value={formik.values.freeSeats}
                      onChange={props => {
                        formik.handleChange(props);
                        formik.handleBlur(props);
                      }}
                      onBlur={formik.handleBlur}
                    />
                    <br></br>
                    <TextField
                      variant="outlined"
                      margin="normal"
                      id="numberPlate"
                      name="numberPlate"
                      helperText={formik.touched.numberPlate ? formik.errors.numberPlate : ''}
                      error={formik.touched.numberPlate && Boolean(formik.errors.numberPlate)}
                      label="Number Plate"
                      value={formik.values.numberPlate}
                      onChange={props => {
                        formik.handleChange(props);
                        formik.handleBlur(props);
                      }}
                      onBlur={formik.handleBlur}
                    />
                    <br></br>
                    <TextField
                      variant="outlined"
                      margin="normal"
                      id="userId"
                      name="userId"
                      helperText={formik.touched.userId ? formik.errors.userId: ''}
                      error={formik.touched.userId && Boolean(formik.errors.userId)}
                      label="User Id"
                      value={formik.values.userId}
                      onChange={props => {
                        formik.handleChange(props);
                        formik.handleBlur(props);
                      }}
                      onBlur={formik.handleBlur}
                    />
                    <br></br>
                    <CustomButton                    
                      text={'Add'}
                    />
                  </div>
                </Form>
      </div>
    );
  }

You can use parseInt(freeSeats) to convert a string to a number.您可以使用parseInt(freeSeats)将字符串转换为数字。

Please bear in mind:请记住:

  • In some cases for example if the number in the string is preceded by a 0, this may give you an incorrect value as there are various rules to determine whether the number in the string is binary, hexadecimal (base 6) or octal (base 8) instead of our standard base 10 counting system.在某些情况下,例如,如果字符串中的数字以 0 开头,这可能会给您一个不正确的值,因为有各种规则可以确定字符串中的数字是二进制、十六进制(以 6 为基数)还是八进制(以 8 为基数) ) 而不是我们标准的以 10 为基数的计数系统。 If this happens you'll need to add a second parameter to the method telling it the number is in base 10: parseInt(freeSeats, 10)如果发生这种情况,您需要在方法中添加第二个参数,告诉它数字以 10 为底: parseInt(freeSeats, 10)
  • If the string is incorrectly formed or empty, you could still end up with the values NaN or undefined.如果字符串格式不正确或为空,您仍然可能会得到值 NaN 或 undefined。 You may want to put checks in against these values before trying to use them.在尝试使用它们之前,您可能需要检查这些值。

There is no Number type in graphql (check docs)... probably should be Int or even ID! graphql 中没有Number类型(检查文档)......可能应该是Int甚至ID!

Defining type Number can be not enough in typescript... https://spin.atomicobject.com/2018/11/05/using-an-int-type-in-typescript/Number ...

If Int is enough (for graphQL) then at least do conversion here:如果 Int 就足够了(对于 graphQL),那么至少在这里进行转换:

addVehicle({
    variables: {
      freeSeats: parseInt(freeSeats),

import { Int } from "type-graphql";

Changing the type from Number to Int within the mutation worked.在突变中将类型从 Number 更改为 Int 有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM