天天看點

GraphQL入門2

将伺服器端的代碼更新了一下:

var GraphQLSchema = require('graphql').GraphQLSchema;

var GraphQLObjectType = require('graphql').GraphQLObjectType;

var GraphQLString = require('graphql').GraphQLString;

var GraphQLList = require('graphql').GraphQLList;

var fetch = require('node-fetch');

require("babel-polyfill");

var BASE_URL = 'http://localhost:3000';

var persons = [

    { id: "1", first_name: "Jack", last_name: "Zhang" , department: "Depart1", friends: [1] },

    { id: "2", first_name: "Tom", last_name: "Wang" , department: "Depart2", friends: [1, 2] }

];

function getPersonByUrl(args, relativeURL) {

    var person = persons.find(function (item) {

        if (args.id) {

            return item.id == args.id;

        }

        if (args.department) {

            return item.department == args.department;

    });

    return person;

    //fetch('${BASE_URL}${relativeURL}')

    //    .then(function (res) { return res.json() })

    //    .then(function (json) { return json.person })

}

function getFriendByPersonId(friendID) {

        return item.id == friendID;

var PersonType = new GraphQLObjectType( {

    name: 'Person',

    description: '...',

    fields: ()=>({

        id: {

            type: GraphQLString,

            resolve : function (person) {

                return person.first_name;

            }

        },

        firstName: {

        lastName: {

                return person.last_name;

        department: {

                return person.department;

        //email: { type: GraphQLString },

        //userName: { type: GraphQLString },

        //id: { type: GraphQLString },

        friends: {

            type: new GraphQLList(PersonType),

            resolve: function (person) {

                return person.friends.map(getFriendByPersonId);

    })

});

var QueryType = new GraphQLObjectType({

    name: 'Query',

    desription: '...',

    fields: {

        person: {

            type: PersonType,

            args: {

                id: { type: GraphQLString },

                department: { type: GraphQLString }

            },

            resolve: function (obj, args, context, info) { return getPersonByUrl(args, null); }

    }

var GraphQLSchemaObj = new GraphQLSchema({

    query: QueryType

module.exports = GraphQLSchemaObj;

主要有以下幾處更改:

将模拟的資料源persons單獨提出來成為一個全局變量.

資料源中增加了department等幾個屬性.

getPersonByUrl函數支援id和department參數.

增加了getFriendByPersonId函數用來解析friends屬性.

PersonType的fields屬性使用了()=>來解決friends屬性中使用本類型時本類型尚未初始化的問題.

下面是用戶端的測試代碼:

app.js

console.log('Hello world');

////Arguments

//var Test1 = require('./Test1');

//Test1.Execute();

////Alias

//var Test2 = require('./Test2');

//Test2.Execute();

////Alias with sub-selection

//var Test3 = require('./Test3');

//Test3.Execute();

////Fragments

//var Test4 = require('./Test4');

//Test4.Execute();

//Variblies

//var Test5 = require('./Test5');

//Test5.Execute();

//Directives

//var Test6 = require('./Test6');

//Test6.Execute();

具體的測試類:

Alias:

//Test2: Aliases 

var gRequest = require('graphql-request').request;

exports.Execute = function () {

    const query = '{'

                + '  Depart1Person: person(department: "Depart1") {'

                + '    firstName,'

                + '    lastName,'

                + '    department'

                + '  }'

                + '  Depart2Person: person(department: "Depart2") {'

                + '    department'

                + '}';

    gRequest('http://localhost:1337/graphql/graphql', query).then(function (data) { console.log(data) });

};

運作結果如下:

{ Depart1Person: { firstName: 'Jack', lastName: 'Zhang', department: 'Depart1' },

  Depart2Person: { firstName: 'Tom', lastName: 'Wang', department: 'Depart2' } }

Aliases -- sub selection

//Test3: Aliases -- sub selection

var util = require('util');

                + '    department,'

                + '    friends'

                + '    {'

                + '     firstName,'

                + '     lastName'

                + '    }'

                + '    department,'

                + '     firstName,'

                + '    }'   

    gRequest('http://localhost:1337/graphql/graphql', query).then(function (data) {

        console.log(util.inspect(data, { showHidden: false, depth: null }))

{ Depart1Person:

   { firstName: 'Jack',

     lastName: 'Zhang',

     department: 'Depart1',

     friends: [ { firstName: 'Jack', lastName: 'Zhang' } ] },

  Depart2Person:

   { firstName: 'Tom',

     lastName: 'Wang',

     department: 'Depart2',

     friends:

      [ { firstName: 'Jack', lastName: 'Zhang' },

        { firstName: 'Tom', lastName: 'Wang' } ] } }

Fragements:

//Test4: Fragements

    var query = '{'

                + '    ...personFields'

                + '}'

                + ''

                + 'fragment personFields on Person {'

                + '  firstName,'

                + '  lastName,'

                + '  department,'

                + '  friends{'

                + '    lastName'

    //gRequest('http://localhost:1337/graphql/graphql', query).then(function (data) { console.log(data) });

Varibles:

//Test5: Variables

    var query = 'query PersonWithDept($dept: String) {'

            + ' 

person(department: $dept) {'

            + '   

...personFields'

}'

            + '}'

            + ''

            + 'fragment personFields on Person {'

firstName,'

lastName,'

            + '  department,'

friends{'

lastName'

            + '}';

            var varibles =

            {

                "dept": "Depart1"

            };

    //gRequest('http://localhost:1337/graphql/graphql',

query).then(function (data) { console.log(data) });

    gRequest('http://localhost:1337/graphql/graphql', query, varibles).then(function (data) {

        console.log(util.inspect(data, {

showHidden: false, depth: null }))

{ person:

     friends: [ { firstName:

'Jack', lastName: 'Zhang' } ] } }   

Directives:

//Test6: Directives 

    var query = 'query PersonWithDept($dept: String, $withFriends:

Boolean!) {'

                + '  person(department: $dept) {'

                + 'fragment personFields on

Person {'

                + '  friends @include(if: $withFriends){'

                + '}' ;

        var varibles1 =

        {

            "dept": "Depart1",

            "withFriends": true

        };

        var varibles2 =

            "withFriends": false

    gRequest('http://localhost:1337/graphql/graphql', query, varibles1).then(function (data) {

    gRequest('http://localhost:1337/graphql/graphql', query, varibles2).then(function (data) {

{ person: { firstName: 'Jack', lastName: 'Zhang', department:

'Depart1' } }

     department: 'Depart1',

'Jack', lastName: 'Zhang' } ] } }

注意用戶端代碼中使用了,是為了列印出json的子對象,