Dưới đây là triển khai nút js đơn giản.
khách hàng 'graphiql' đủ tốt cho hoạt động phát triển.
1. run npm install
2. start server with "node server.js"
3. hit "http://localhost:8080/graphiql" for graphiql client
server.js
var graphql = require ('graphql').graphql
var express = require('express')
var graphQLHTTP = require('express-graphql')
var Schema = require('./schema')
// This is just an internal test
var query = 'query{starwar{name, gender,gender}}'
graphql(Schema, query).then(function(result) {
console.log(JSON.stringify(result,null," "));
});
var app = express()
.use('/', graphQLHTTP({ schema: Schema, pretty: true, graphiql: true }))
.listen(8080, function (err) {
console.log('GraphQL Server is now running on localhost:8080');
});
schema.js
//schema.js
var graphql = require ('graphql');
var http = require('http');
var StarWar = [
{
"name": "default",
"gender": "default",
"mass": "default"
}
];
var TodoType = new graphql.GraphQLObjectType({
name: 'starwar',
fields: function() {
return {
name: {
type: graphql.GraphQLString
},
gender: {
type: graphql.GraphQLString
},
mass: {
type: graphql.GraphQLString
}
}
}
});
var QueryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: function() {
return {
starwar: {
type: new graphql.GraphQLList(TodoType),
resolve: function() {
return new Promise(function (resolve, reject) {
var request = http.get({
hostname: 'swapi.co',
path: '/api/people/1/',
method: 'GET'
}, function(res){
res.setEncoding('utf8');
res.on('data', function(response){
StarWar = [JSON.parse(response)];
resolve(StarWar)
console.log('On response success:' , StarWar);
});
});
request.on('error', function(response){
console.log('On error' , response.message);
});
request.end();
});
}
}
}
}
});
module.exports = new graphql.GraphQLSchema({
query: QueryType
});
Ứng dụng khách được thiết kế để chạy trong trình duyệt. Với các công cụ graphql và graphql-server-express (máy chủ apollo trước đây), bạn có thể thực hiện hầu hết mọi thứ. – Hosar
Vì vậy, nếu tôi muốn máy chủ tạo các truy vấn graphql cho một số máy chủ khác thì sao? Sau đó, tôi cần một thư viện client graphql chạy trên máy chủ, có? – Josh
Đây là 8 tháng trước ... nếu bạn có bất kỳ thông tin chi tiết nào từ khi bạn có thể chia sẻ? – YakirNa