Какова правильная форма POST-запроса curl к API-интерфейсу GraphQL gqlgen? - PullRequest
0 голосов
/ 20 января 2019

Я создал простой API-интерфейс GraphQL, очень похожий на учебник gqlgen " Getting Started ". Я могу успешно запросить его с помощью curl. Но я не могу понять запрос curl на мутацию.

schema.graphql:

type Screenshot {
  id: ID!
  url: String!
  filename: String!
  username: String!
  description: String
}

input NewScreenshot {
  id: ID!
  url: String!
  filename: String!
  username: String!
  description: String
}

type Mutation {
  createScreenshot(input: NewScreenshot!): Screenshot!
  deleteScreenshot(id: ID!): String!
}

type Query {
  screenShots(username: String!): [Screenshot!]!
}

models_gen.go:

type NewScreenshot struct {
    ID          string  `json:"id"`
    URL         string  `json:"url"`
    Filename    string  `json:"filename"`
    Username    string  `json:"username"`
    Description *string `json:"description"`
}

type Screenshot struct {
    ID          string  `json:"id"`
    URL         string  `json:"url"`
    Filename    string  `json:"filename"`
    Username    string  `json:"username"`
    Description *string `json:"description"`
}

resolver.go:

func (r *mutationResolver) CreateScreenshot(ctx context.Context, input NewScreenshot) (Screenshot, error) {
    id, err := uuid.NewV4()
    shot := Screenshot{
        ID:          id.String(),
        Description: input.Description,
        URL:         input.URL,
        Filename:    input.Filename,
        Username:    input.Username,
    }

    return shot, nil
}

Я пробовал:

  • Просмотр документации gqlgen , Схема GraphQL , Как GraphQL и несколько примеров, таких как this и это . И поиск в Google за 1,5 дня.

  • Перебирая через много, много разных форм в моем запросе локона. Этот кажется самым близким:

    curl -v http://localhost:8080/query
    -H "Content-Type: application/json"
    -d '{ "query":
        { "createScreenshot":
            {"username": "Odour",
             "url": "google.com",
             "description": "just another screenshot",
             "filename": "testimage"
            }
        }
    }'
    

    Но это не с:

    * timeout on name lookup is not supported
    *   Trying ::1...
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
      0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Connected to localhost (::1) port 8080 (#0)
    > POST /query HTTP/1.1
    > Host: localhost:8080
    > User-Agent: curl/7.47.1
    > Accept: */*
    > Content-Type: application/json
    > Content-Length: 146
    >
    } [146 bytes data]
    * upload completely sent off: 146 out of 146 bytes
    < HTTP/1.1 400 Bad Request
    < Date: Sat, 19 Jan 2019 21:00:15 GMT
    < Content-Length: 149
    < Content-Type: text/plain; charset=utf-8
    <
    { [149 bytes data]
    100   295  100   149  100   146    149    146  0:00:01 --:--:--  0:00:01  145k{"errors":[{"message":"json body could not be decoded: json: cannot unmarshal object into Go struct field params.query of type string"}],"data":null}
    * Connection #0 to host localhost left intact
    

Помощь

1 Ответ

0 голосов
/ 20 января 2019

Значение query в полезной нагрузке JSON должно быть строкой, содержащей запрос GraphQL, а не объектом, который вы используете, например:

$ curl \
  -H "Content-Type: application/json" \
  -d '{ "query": "mutation { createScreenshot(input: { username: \"Odour\" }) { id } }" }' \
  http://localhost:8080/query

Обратите внимание, что вам нужно экранировать двойные кавычки в строке запроса.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...