Laravel Graphql Mutation 时数据验证及复杂格式数据输入 (InputObjectType)
1.使用Laravel Graphql的扩展支持直接添加rules()方法进行数据的验证:
class ConfigMutation extends Mutation
{
protected $attributes = [
'name' => 'ConfigMutation',
'description' => 'A mutation of Config'
];
public function type()
{
return Type::boolean();
}
public function rules()
{
return [
/*验证----------->start*/
'config.aaa' => 'required|array',
]
}
}
2.如歌输入的数据是多层嵌套的json该怎么在args()方法中定义对应的字段呢?目前我使用的是InputObjectType
public function args()
{
return [
'AAA_id' => [
'name' => 'AAA_id', 'type' => Type::nonNull(Type::int()), 'description' => 'AAAid'\
],
'type' => [
'name' => 'type', 'type' => Type::nonNull(GraphQL::type('TypeEnum')), 'description' => '选择的平台'\
],
'config' => [
'name' => 'config', 'type' => Type::nonNull($config), 'description' => '配置'\
]
];
}
上面的config是一个复杂的json数据,每个key对应的值有可能是基本的类型,也有可能是数组,此时可以这样:
$config = new InputObjectType([
'name' => 'ConfigFiltersInput',
'fields' => [
'aa_info' => [
'name' => 'aa_info', 'type' => Type::nonNull($setting), 'description' => 'aaa信息'
],
'aaa_feature' => [
'name' => 'aaa_feature', 'type' => Type::nonNull($setting), 'description' => 'aaa特色'
],
'aaa_ranking' => [
'name' => 'aaa_ranking', 'type' => ($aaa_ranking), 'description' => 'aaa排行'
]
]
]);
上例中$setting也是一个InputObjectType,对应需要定义的数据
通过使用InputObjectType可以灵活处理所有复杂的输入数据,同时如果输入的数据是一个json中的数组该如何处理呢?
'setting' => [
'name' => 'setting', 'type' => Type::nonNull(Type::listOf($filters)), 'description' => '权限'
],
$filters是自己定义的InputObjectType,通过使用listOf可以处理数组数据
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: