Работает ли apollo-клиент на node.js?
Мне нужно графическое приложение libq для работы с node.js для некоторого тестирования и некоторого mashup данных - не в производственной мощности. Я использую apollo везде (react-apollo
, apollo graphql-server-express
). Мои потребности довольно просты.
Является ли apollo-client
жизнеспособным выбором? Я не могу найти примеры или документы об использовании этого в node - если вы знаете о них, поделитесь им.
Или, может быть, мне следует/использовать ссылочный графический клиент на node?
Ответы
Ответ 1
Клиент Apollo должен нормально работать на Node. Вам нужно только установить перекрестную выборку, поскольку предполагается, что fetch
существует.
Вот полная реализация TypeScript Apollo Client, работающего на Node.js.
import ApolloClient from "apollo-boost";
import gql from "graphql-tag";
import { InsertJob } from "./graphql-types";
import 'cross-fetch/polyfill';
const client = new ApolloClient({
uri: "http://localhost:3000/graphql"
});
client.mutate<InsertJob.AddCompany, InsertJob.Variables>({
mutation: gql'mutation insertJob($companyName: String!) {
addCompany(input: { displayName: $companyName } ) {
id
}
}',
variables: {
companyName: "aaa"
}
})
.then(result => console.log(result));
Ответ 2
Вот простая реализация node js.
Клиент 'graphiql' достаточно хорош для развития.
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
});
Ответ 3
В ответ на комментарий @YakirNa:
Я не могу говорить с другими потребностями, которые я описал, но я провел много испытаний. Я закончил все свои тесты в процессе.
Большинство тестов заканчивается тестированием resolver, которое я делаю через jig, который вызывает функцию graphql library graphql
с тестовым запросом, а затем проверяет ответ.
У меня также есть (почти) сквозной тестовый уровень, который работает на уровне обработки HTTP Express. Он создает фальшивый HTTP-запрос и проверяет ответ в процессе. Это все в рамках серверного процесса; ничто не проходит через провод. Я использую это легко, в основном для проверки подлинности JWT и других запросов на уровне запросов, которые не зависят от тела запроса graphql.
Ответ 4
Если кто-то ищет версию JavaScript:
require('dotenv').config();
const gql = require('graphql-tag');
const ApolloClient = require('apollo-boost').ApolloClient;
const fetch = require('cross-fetch/polyfill').fetch;
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const client = new ApolloClient({
link: createHttpLink({
uri: process.env.API,
fetch: fetch
}),
cache: new InMemoryCache()
});
client.mutate({
mutation: gql'
mutation popJob {
popJob {
id
type
param
status
progress
creation_date
expiration_date
}
}
',
}).then(job => {
console.log(job);
})