GraphQL.js數(shù)據(jù)查詢語(yǔ)言
GraphQL.js (GraphQLJS)是 JavaScript 參考實(shí)現(xiàn) GraphQL 的一個(gè)技術(shù)預(yù)覽,F(xiàn)acebook 開(kāi)發(fā)的一種查詢語(yǔ)言,用于在復(fù)雜的應(yīng)用程序的數(shù)據(jù)模型中,描述數(shù)據(jù)要求。
使用示例:
從 npm 安裝 GraphQL.js
npm install graphql
首先,建立GraphQL 型架構(gòu)映射到你的代碼庫(kù)。
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLString
} from 'graphql';var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve: () => 'world'
}
}
})
});
然后,服務(wù)針對(duì)該類型架構(gòu)的查詢結(jié)果。
var query = '{ hello }';
graphql(schema, query).then(result => { // Prints
// {
// data: { hello: "world" }
// }
console.log(result);
});
這將運(yùn)行一個(gè)查詢獲取定義一個(gè)字段。 graphql 功能將首先確保查詢語(yǔ)法和語(yǔ)義有效執(zhí)行,否則報(bào)告錯(cuò)誤。
var query = '{ boyhowdy }';
graphql(schema, query).then(result => { // Prints
// {
// errors: [
// { message: 'Cannot query field boyhowdy on RootQueryType',
// locations: [ { line: 1, column: 3 } ] }
// ]
// }
console.log(result);
});
評(píng)論
圖片
表情
