
如何通過IP欺詐檢測API識別代理IP和VPN連接
id: Int!
title: String!
description: String
}
在這里,Movie 是一個對象類型,其字段包括 id、標題和描述。感嘆號(!)因此,該類型中 id 和 title 是必填字段,而 description 是可選字段。
它是一種特殊的對象類型,為查詢提供入口點。所有查詢都在該對象中定義。
type Query{
# Define queries here
}
獲取 API 中的所有電影,我們將定義一個 movie 查詢:
type Query {
movies: [Movie!]!
}
如您所見,我們還將查詢返回的數據指定為 [Movie!]!。這種語法意味著它將始終返回一個數組,而數組中的每個元素都是一個 movie 對象。
現在,如果我們想獲取一部特定的電影怎么辦?我們可以這樣定義 movie 查詢:
type Query {
movies: [Movie!]!
movie(id: Int!): Movie
}
movie 查詢需要一個 id 參數,即我們要獲取的 movie id。然后返回一個 movie 對象。
現在,我們可以這樣使用這些查詢:
# Fetches all the movies
query movies {
id
title
description
}
# Fetches a particular movie
query movie(id: 200) {
id
title
description
}
定義 GraphQL 突變
與查詢一樣,您可以在突變類型中定義突變
比方說,我們希望允許一個突變來創建一部新 movie。我們可以這樣定義 create Movie 突變:
type Mutation {
createMovie(title: String!, description: String): Movie
}
它將接受標題和描述并創建一部新 movie。最后,它會在響應中返回一個新添加 movie 的 Movie 對象。
我們可以這樣使用突變:
query createMovie(title: "The Matrix", description: "A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.") {
id
title
description
}
如果我們運行這個突變,API 將返回這樣的數據:
{
"data": {
"createMovie": {
"id": 200,
"title": "The Matrix",
"description": "A computer hacker learns from mysterious rebels about the true nature ofhis reality and his role in the war against its controllers."
}
}
}
就是這樣。您可以看到,在模式中定義查詢和突變是多么容易。現在,您只需創建解析器函數來處理它們,您的 API 就可以正常運行了。
原文鏈接:How to Define GraphQL Queries and Mutations?