У меня Призма 1.34. для разработки API. Тестирование через локальную игровую площадку. Извините заранее за длинный текст, не могу понять, где я ошибся.
У меня есть следующая схема, представляющая иерархию. Шаблон сценария состоит из шаблонов карт, а карты включают шаблоны задач:
type ScriptTemplate {
id: ID!
name: String!
cards: [CardTemplate!]
input: String!
output: String!
}
type CardTemplate {
id: ID!
title: String!
description: String
tasks: [TaskTemplate!]
}
input ExistingCardTemplateInput {
id: ID!
}
input NewCardTemplateInput {
title: String!
description: String!
tasks: [NewTaskTemplateInput!]
}
type TaskTemplate {
id: ID!
label: String!
description: String!
cards: [CardTemplate!]
}
input ExistingTaskTemplateInput {
id: ID!
}
input NewTaskTemplateInput {
label: String!
description: String!
}
Соответствующие мутации:
type Mutation {
createScriptTemplate(name: String!, input: String!, output: String!, cards: [ExistingCardTemplateInput!], new_cards: [NewCardTemplateInput!]): ScriptTemplate
createCardTemplate(title: String!, description: String! tasks:[ExistingTaskTemplateInput!], new_tasks:[NewTaskTemplateInput!]): CardTemplate
createTaskTemplate(label: String!, description: String! cards:[ExistingCardTemplateInput!]): TaskTemplate
}
В общем, если я пытаюсь использовать мутацию createTaskTemplate или мутацию createCardTemplate - все работает нормально. Я могу создавать эти объекты, включая вложенную мутацию, создающую новую карту с новыми задачами в ней или связывающую уже существующие задачи. Или существующую карту для вновь созданной задачи. Вот почему явно определены типы ввода: ExistingTaskTemplateInput, NewTaskTemplateInput и NewCardTemplateInput.
Все работает как положено, когда я пытаюсь создать новый скрипт с включением новой карты или подключением ее к существующей, а также.
Однако, если я пытаюсь создать Script, Card и включить в него новые задачи, я получаю сообщения об ошибках выше.
mutation{
createScriptTemplate(
name: "Script via API_H2"
input: "Something describing initial state"
output: "Something describing required state at the end"
cards: [
{
id: "cjycl2nup00ta0703sd0kd8oa"
},
{
id: "cjye3ryee01ey070383sxaoxz"
}
]
new_cards:[
{
title:"New card via scriptis2"
description:"desc"
tasks: [
{
description: "test dewscription"
label: "test label"
}
]
},
{
title:"New card through scriptos2"
description: "desc"
}
]
){
id
name
input
output
createdAt
updatedAt
cards{
id
title
tasks{
id
label
}
}
}
}
у меня ошибка:
{
"data": {
"createScriptTemplate": null
},
"errors": [
{
"message": "Variable '$data' expected value of type 'ScriptTemplateCreateInput!' but got:
{\"name\":\"First Script through API_H2\",\"input\":\"Something describing initial state\",\"output\":\"Something describing requred state at the end\",\"cards\":{\"connect\":[{\"id\":\"cjycl2nup00ta0703sd0kd8oa\"},{\"id\":\"cjye3ryee01ey070383sxaoxz\"}],\"create\":[{\"title\":\"New card via scriptis2\",\"description\":\"desc\",\"tasks\":[{\"label\":\"test label\",\"description\":\"test dewscription\"}]},{\"title\":\"New card through scriptos2\",\"description\":\"desc\"}]}}.
Reason: 'cards.create[0].tasks'
Expected 'TaskTemplateCreateManyWithoutCardsInput', found not an object. (line 1, column 11):\nmutation ($data: ScriptTemplateCreateInput!) {\n ^",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"createScriptTemplate"
]
}
]
}
Фактический запрос выглядит так (через console.info):
{ name: 'First Script through API_H2',
input: 'Something describing initial state',
output: 'Something describing requred state at the end',
cards:
{ connect:
[ [Object: null prototype] { id: 'cjycl2nup00ta0703sd0kd8oa' },
[Object: null prototype] { id: 'cjye3ryee01ey070383sxaoxz' } ],
create:
[ [Object: null prototype] {
title: 'New card via scriptis2',
description: 'desc',
tasks:
[ [Object: null prototype] { label: 'test label', description: 'test dewscription' } ] },
[Object: null prototype] { title: 'New card through scriptos2', description: 'desc' } ] } }
Похоже, я пропустил бит {connect or create} для поля tasks.
Однако, когда я изменяю его, чтобы он выглядел так:
tasks: {create: [
{
description: "test dewscription"
label: "test label"
}
]
}
Я получаю сообщение об ошибке Field \"create\" is not defined by type NewTaskTemplateInput и Field NewTaskTemplateInput.label and description of required type String! was not provided
mutation{
createScriptTemplate(
name: "Script via API_H2"
input: "Something describing initial state"
output: "Something describing required state at the end"
cards: [
{
id: "cjycl2nup00ta0703sd0kd8oa"
},
{
id: "cjye3ryee01ey070383sxaoxz"
}
]
new_cards:[
{
title:"New card via scriptis2"
description:"desc"
},
{
title:"New card through scriptos2"
description: "desc"
}
]
){
id
name
input
output
createdAt
updatedAt
cards{
id
title
tasks{
id
label
}
}
}
}
Проверил сгенерированную схему, проблем не обнаружил.
input TaskTemplateCreateManyWithoutCardsInput {
create: [TaskTemplateCreateWithoutCardsInput!]
connect: [TaskTemplateWhereUniqueInput!]
}
input TaskTemplateCreateWithoutCardsInput {
id: ID
label: String!
description: String!
}
Похоже, я путаю схему, которую я определил в файлах gql, и ту, которую я снова делаю запросы, но не знаю, в каком направлении идти.
@Errorname извините, мой плохой неправильный пример. на самом деле не имеет значения тот же результат с «создать». Чего я не могу понять, так это того, что я явно определил типы ввода для tasks как [NewTaskTemplateInput!]. почему Prisma в один момент проверяет его на этот тип, но в то же время проверяет его на TaskTemplateCreateWithoutCardsInput ?


Сначала опишите весь процесс запроса.
The above image is taken from Prisma Basics in the official Prisma documentation.
Как показано на этом рисунке, localhost playground — это client на рисунке. Server, к которому обращается localhost playground, — это API Server на рисунке, то есть Prisma Client. Вот первое соединение, зеленая стрелка на картинке.
Prisma Client получает данные из базы данных, обращаясь к Prisma Server. Это второе соединение, желтая стрелка на рисунке.
Процесс потока данных, отправленный от localhost playground к API Server для завершения первой передачи соединения, а затем обработанный resolve, используйте Prisma Client для отправки Prisma Server для завершения второй передачи соединения. Prisma Server извлекает данные из Database в соответствии с запрошенными данными и возвращает их в API Server, завершает прием второго соединения. API Server возвращает данные localhost playground, завершая принятие первого соединения. Полный процесс завершен.
В процессе использования Prisma мы определяем две схемы, одна для определения Prisma Server, имя обычно datamodel.prisma. Другой используется для определения Prisma Client, если он определен в файле, обычно с именем schema.graphql, также может быть определен в файле JS через строку шаблона, есть и другие способы, здесь подробно не обсуждаются. То, что вы показываете, принадлежит Client Schema.
Успешное завершение этого процесса требует, чтобы данные, отправляемые каждой частью, были правильными.
Ваша первая ошибка произошла при отправке второго соединения. Данные, отправленные из API Server, не соответствуют определению схемы в Prisma Server.
Вторая ошибка заключается в том, что данные, отправленные из localhost playground, не соответствуют определению схемы в API Server при отправке первого соединения.
Предположим следующую архитектуру
# datamodel.prisma
type User {
id: @id!
name: String!
post: [Post!]!
}
type Post {
id: @id!
title: String!
}
# schema.graphql
input CreatePost {
title: String!
}
type Mutation {
createUser(name: String!,posts:[CreatePost])
}
Используйте следующую мутацию Создать пользователя
mutation {
createUser(name: "prisma", posts: [{ title: "test" }]) {
id
name
}
}
При отправке с localhost playground на API Server данные следующие
{
"name": "prisma",
"posts": [{ "title": "test" }]
}
Если вы отправляете эти данные напрямую в Prisma Server, они не соответствуют определению Prisma Server. Вам необходимо преобразовать данные в определение, соответствующее схеме Prisma Server.
{
"name": "prisma",
"posts": { "create": [{ "title": "test" }] }
}
Затем отправьте его на Prisma Server через Prisma Client.
const resolve = {
Mutation: {
createUser: async (_, args) => {
const userCreateInput = {
name: args.name,
posts: {
create: args.posts,
},
}
return await prisma.createUser(userCreateInput)
},
},
}
Таким образом, окончательные данные поступают в базу данных через Prisma Server.
Ознакомьтесь с определением createScriptTemplate в API Server. Должно быть так, что он не преобразовывал полученные данные в ошибку, вызванную форматом, требуемым API Server.
Я думаю, вы должны либо использовать
createвtasksс меткой и описанием, либоconnectтолько сid. Здесь вы используетеconnectс меткой и описанием, но без идентификатора.