这个错误通常表示您在需要非空ID的位置上提供了null值,可能是由于代码中的逻辑错误或处理错误的情况导致的。为了解决这个问题,您需要在某些情况下检查是否存在null值,并通过处理这些值来避免出现问题。
以下是一个示例,演示如何对可能出现null值的GraphQL mutation进行校验,并在必要时将其清理掉:
import { API, graphqlOperation } from 'aws-amplify';
import { createTodo } from './graphql/mutations';
async function createNewTodo(title, description, dueDate) {
try {
const input = {
title: title,
description: description,
dueDate: dueDate,
// Set the following value to null intentionally to trigger an error
user: null
};
// Check if 'input' contains null values and remove them
Object.keys(input).forEach((key) => (input[key] == null) && delete input[key]);
const newTodo = await API.graphql(graphqlOperation(createTodo, { input }));
console.log('New todo created: ', newTodo.data.createTodo);
} catch (err) {
console.log('Failed to create new todo: ', err);
}
}
在这个示例中,我们首先定义一个包含ID字段的输入,然后设置其中一个字段为null。接下来,我们使用Object.keys()遍历所有的字段,并检查它们是否为null。如果存在null值,我们将删除它们。最后,我们将清理后的输入对象作为参数传递给GraphQL mutation并执行操作。这样,我们就可以避免AWS Amplify GraphQL变量“input”被强制转换为非空类型“ID!”的Null值的问题。