smallorange-graphql-buffered-queries
v1.0.4
Published
Query buffer for GraphQl
Downloads
6
Readme
Small Orange GraphQL Buffered Queries
This package creates a buffered query for GraphQL, it means debounce query execution to make only one request to the backend. It is based on RxJS, so your transport layer might be an Observable, in this sample we use https://github.com/feliperohdee/smallorange-graphql-rxjs but you can create one by yourself using Ajax, Websocket, mqtt, ... it just needs to be a RxJS Observable following the simple method signature (query, variables) => Observable.
API
constructor(runner: (query, variables) => Observable, debounceTime: number = 10); // debounceTime is the time to wait to bufferize all queries before they are sent to the backend;
queue(query: string, variables?: object): Observable;
Usage
const graphql = 'smallorange-graphql-rxjs';
const schema = new GraphQLSchema({
name: 'Root',
query: new GraphQLObjectType({
name: 'Query',
fields: {
conversation: {
type: new GraphQLObjectType({
name: 'Conversation',
fields: {
id: {
type: GraphQLString
}
}
}),
args: {
id: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (source, args) => args
},
user: {
type: new GraphQLObjectType({
name: 'User',
fields: {
id: {
type: GraphQLString
}
}
}),
args: {
id: {
type: GraphQLString
}
},
resolve: (source, args) => args
}
}
}),
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
insertConversation: {
type: new GraphQLObjectType({
name: 'InsertConversation',
fields: {
id: {
type: GraphQLString
}
}
}),
args: {
id: {
type: new GraphQLNonNull(GraphQLString)
},
userId: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (source, args) => args
}
}
})
});
const runner = (query, variables) => graphql({query, variables});
const buffered = new Buffered(runner, 10 /* default debounce time */);
const simpleQuery = `{
user {
id
}
}`;
const query = `query ($id: String = "myId"){
conversation(id: $id){
id
}
user(id: $id) {
id
}
}`;
const mutation = `mutation ($id: String = "myId", $userId: String = "userId"){
insertConversation(id: $id, userId: $userId){
id
}
}`;
buffered.queue(query, {
id: 'queryId'
})
.subscribe(console.log);
buffered.queue(simpleQuery, {
id: 'queryId'
})
.subscribe(console.log);
buffered.queue(mutation, {
id: 'mutationId'
})
.subscribe(console.log);
// buffered query will call the backend once for all queries, and once for all mutations, and return their results via subscriptions, easy as that!