├── src
├── socketdata.js
├── client-sockets.js
├── sockets.js
├── jobqueue.js
└── subql.js
├── experimentation
├── index.html
├── sockets.js
├── server.js
└── jobqueueserver.js
├── .npmignore
├── .gitignore
├── LICENSE
├── package.json
├── README.md
└── test
└── test.js
/src/socketdata.js:
--------------------------------------------------------------------------------
1 | const connected = {};
2 |
3 | module.exports = { connected };
4 |
--------------------------------------------------------------------------------
/experimentation/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Testing
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/client-sockets.js:
--------------------------------------------------------------------------------
1 | var socket;
2 | var socketid;
3 |
4 | function subscribe(uri, query, variables = null, callback) {
5 | if (!socket) {
6 | socket = io(uri);
7 | socket.on('init', ({id}) => {
8 | socketid = id;
9 | socket.on(socketid, (data) => { callback(data) });
10 | socket.emit(socketid, { query });
11 | });
12 | }
13 | }
14 |
15 | function unsubscribe() {
16 | socket.emit('unsubscribe', { socketid });
17 | }
18 |
19 | function graphql(query){
20 | socket.emit('mutation', { query });
21 | }
22 |
23 | // subscribe('http://localhost:4000', '{ getMessage(id: 0) { content, author} }', null, function (data) {
24 | // console.log(data);
25 | // });
26 |
27 | module.exports = {subscribe, unsubscribe, graphql};
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 |
6 | # Runtime data
7 | pids
8 | *.pid
9 | *.seed
10 |
11 | # Directory for instrumented libs generated by jscoverage/JSCover
12 | lib-cov
13 |
14 | # Coverage directory used by tools like istanbul
15 | coverage
16 |
17 | # nyc test coverage
18 | .nyc_output
19 |
20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
21 | .grunt
22 |
23 | # node-waf configuration
24 | .lock-wscript
25 |
26 | # Compiled binary addons (http://nodejs.org/api/addons.html)
27 | build/Release
28 |
29 | # Dependency directories
30 | node_modules
31 | jspm_packages
32 |
33 | # Optional npm cache directory
34 | .npm
35 |
36 | # Optional REPL history
37 | .node_repl_history
38 |
39 | # folders to ignore
40 | test
41 | experimentation
42 |
43 | # files to ignore
44 | situation.js
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 |
6 | # Runtime data
7 | pids
8 | *.pid
9 | *.seed
10 |
11 | # Directory for instrumented libs generated by jscoverage/JSCover
12 | lib-cov
13 |
14 | # Coverage directory used by tools like istanbul
15 | coverage
16 |
17 | # nyc test coverage
18 | .nyc_output
19 |
20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
21 | .grunt
22 |
23 | # node-waf configuration
24 | .lock-wscript
25 |
26 | # Compiled binary addons (http://nodejs.org/api/addons.html)
27 | build/Release
28 |
29 | # Dependency directories
30 | node_modules
31 | jspm_packages
32 |
33 | # Optional npm cache directory
34 | .npm
35 |
36 | # Optional REPL history
37 | .node_repl_history
38 |
39 | # folders to ignore
40 | test
41 | # experimentation # leave this in for git
42 |
43 | # files to ignore
44 | situation.js
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License
2 |
3 | Copyright (c) 2016 SubQL
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "subql",
3 | "version": "0.0.4",
4 | "description": "SubQL enables real time data subscriptions to graphQL APIs",
5 | "main": "src/subql.js",
6 | "scripts": {
7 | "test": "mocha"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "git+https://github.com/CMDco/subql.git"
12 | },
13 | "keywords": [
14 | "graphql",
15 | "api",
16 | "realtime",
17 | "rest",
18 | "restful",
19 | "middleware",
20 | "data",
21 | "node",
22 | "express",
23 | "reactive",
24 | "socket",
25 | "sockets",
26 | "socketio",
27 | "socket.io",
28 | "cabotage"
29 | ],
30 | "author": "Martin-Ting",
31 | "license": "MIT",
32 | "bugs": {
33 | "url": "https://github.com/CMDco/subql/issues"
34 | },
35 | "homepage": "https://github.com/CMDco/subql#readme",
36 | "dependencies": {
37 | "express-graphql": "^0.6.1",
38 | "graphql": "^0.8.2",
39 | "object-hash": "^1.1.5",
40 | "rxjs": "^5.0.0-rc.5",
41 | "socket.io": "^1.7.1"
42 | },
43 | "devDependencies": {
44 | "body-parser": "^1.15.2",
45 | "chai": "^3.5.0",
46 | "express": "^4.14.0",
47 | "express-graphql": "^0.6.1",
48 | "mocha": "^3.2.0",
49 | "sinon": "^1.17.6",
50 | "sinon-chai": "^2.8.0"
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/sockets.js:
--------------------------------------------------------------------------------
1 | var io;
2 | var http = require('http')
3 | var { handleSubscribe, handleDisconnect, getSchema, getRoot} = require('./subql.js');
4 | var { connected } = require('./socketdata.js');
5 | const graphql = require('graphql');
6 |
7 | const debugLog = false;
8 |
9 | function setup(server) {
10 | io = require('socket.io')(server);
11 | io.on('connection', function (socket) {
12 | connected[socket.id] = { socket };
13 | socket.emit('init', { id: socket.id });
14 | socket.on(socket.id, function (query) {
15 | debug(`socket.on(${socket.id}) :: [${socket.id}] made subscription request`);
16 | handleSubscribe(query, socket.id);
17 | });
18 | socket.on('disconnect', function(){
19 | handleDisconnect(socket.id);
20 | debug(`socket.on(disconnect) :: [${socket.id}] disconnected`);
21 | });
22 | socket.on('mutation', (data) => {
23 | console.log(`socket event[mutation] :: recieved query from ${socket.id}\n${data}`);
24 | graphql.graphql(
25 | graphql.buildSchema(getSchema()),
26 | data.query,
27 | getRoot()
28 | ).then((result) => {
29 | console.log(`socket event[mutation] :: result for ${socket.id}\n${result}`);
30 | console.log(result);
31 | });
32 | });
33 | });
34 | }
35 |
36 | function debug(debugStr){
37 | if(debugLog) console.log(debugStr);
38 | }
39 |
40 | module.exports = { setup };
--------------------------------------------------------------------------------
/experimentation/sockets.js:
--------------------------------------------------------------------------------
1 | var socket;
2 | var socketid;
3 |
4 | function subscribe(uri, query, variables = null, callback) {
5 | console.log(`subscribing to ${query}`);
6 | if (!socket) {
7 | socket = io(uri);
8 | socket.on('init', ({id}) => {
9 | socketid = id;
10 | socket.on(socketid, (data) => { callback(data) });
11 | socket.emit(socketid, { query });
12 | });
13 | }else{
14 | socket.emit(socketid, {query});
15 | }
16 | }
17 |
18 | function unsubscribe() {
19 | socket.emit('unsubscribe', { socketid });
20 | }
21 |
22 | function subql(query){
23 | socket.emit('mutation', { query });
24 | }
25 |
26 | // subscribe('http://localhost:4000/', `
27 | // {
28 | // getMessage(id: 0){
29 | // id, content, author
30 | // }
31 | // }
32 | // `, null, function (data) {
33 | // console.log(data);
34 | // });
35 |
36 |
37 | //subscribe(null, '{ getMessages(id: 0, test:"testarg", another:"anotherarg", something:"somethingarg"){content, author} }', null, function (data) {
38 |
39 | // subscribe(null, `
40 | // {
41 | // getMessage(id: 0){
42 | // id
43 | // content
44 | // author
45 | // date{
46 | // year
47 | // }
48 | // }
49 | // getMessages{
50 | // content
51 | // date{
52 | // day
53 | // }
54 | // }
55 | // }
56 | // `, null, function (data) {
57 | // console.log(data);
58 | // });
59 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SubQL
2 | SubQL enables real time data subscriptions to GraphQL APIs.
3 |
4 | Note from the [Author](https://github.com/Martin-Ting): On March 6, the specification for GraphQL Subscriptions was merged into the official RFC for GraphQL. The GraphQL-js library should be updated soon with this functionality. As small as this open source project is for realtime GraphQL, even with all it's caveats and lack of support, it was great fun tackling this problem. The guys over on the Apollo team have also done a lot of great work with realtime GraphQL so check out that project too. @stubailo from the Apollo team released a great [article](https://dev-blog.apollodata.com/the-next-step-for-realtime-data-in-graphql-b564b72eb07b) about this.
5 |
6 | [](https://badge.fury.io/js/subql)
7 |
8 | ## Installation
9 | ```npm install --save subql```
10 |
11 | ## Disclaimer
12 | The SubQL is in alpha. Every feature should be considered experimental and has the possibility of breaking or being removed in the future. If you have any questions, comments, suggestions for features, or any other concerns please contact [Martin-Ting](https://github.com/martin-ting). Our team (listed below) is very open to suggestions and feedback and encourage it if you try our library out. We hope to provide a great tool for graphQL developers to bring real time data to their APIs.
13 |
14 | ## Documentation
15 | Documentation for SubQL is available on the [SubQL Wiki](https://github.com/CMDco/SubQL/wiki) page
16 |
17 | ## Contributing
18 | ***Commit Style Guide***
19 | [Udacity git commit message style guide](https://udacity.github.io/git-styleguide/) for commit messages.
20 |
21 | ## Contributors
22 | - [Martin Ting](https://github.com/Martin-Ting)
23 | - [Ceasar Hernandez](https://github.com/cesarhernar)
24 | - [Dean Edwards](https://github.com/deancode)
25 |
26 | ## License
27 | [GPL-3.0](https://opensource.org/licenses/GPL-3.0)
28 |
--------------------------------------------------------------------------------
/test/test.js:
--------------------------------------------------------------------------------
1 | const chai = require('chai');
2 | const sinon = require('sinon');
3 | const sinonChai = require('sinon-chai');
4 |
5 | const {
6 | parse,
7 | validate,
8 | } = require('graphql');
9 |
10 | const {
11 | registerResolver,
12 | getRoot,
13 | registerType,
14 | parseSchema,
15 | handleSubscribe,
16 | handleDisconnect,
17 | triggerType
18 | } = require('../src/subql.js');
19 |
20 | chai.use(sinonChai);
21 | const expect = chai.expect;
22 | const assert = chai.assert;
23 |
24 | describe('SubQL Tests', () => {
25 | describe('Unit Test :: registerResolver', () => {
26 | it('should throw an error when no arguments are passed in.', done => {
27 | done();
28 | });
29 | it('should throw an error when anonymous functions are passed in', done => {
30 | done();
31 | });
32 | it('should create keys for all functions passed in', done => {
33 | done();
34 | });
35 | });
36 |
37 | describe('Unit Test :: getRoot', () => {
38 | it('should return a root object', done => {
39 | done();
40 | });
41 | });
42 |
43 | describe('Unit Test :: wrapResolver', () => {
44 | it('should wrap functions according to type', done => {
45 | done();
46 | });
47 | it('should return a function that triggers the proper type', done =>{
48 | done();
49 | });
50 | });
51 |
52 | describe('Unit Test :: parseSchema', () => {
53 | it('should throw an error when nothing is passed in', done => {
54 | done();
55 | });
56 | it('should populate the operations object when a valid schema is passed in', done =>{
57 | done();
58 | });
59 | });
60 | describe('Unit Test :: handleDisconnect', () => {
61 | it('should remove something from connected object', done => {
62 | done();
63 | });
64 | it('should be refactored to another file', done => {
65 | done();
66 | });
67 | });
68 | describe('Unit Test :: triggerType', () => {
69 | it('should trigger socket communications based on type', done => {
70 | done();
71 | });
72 | })
73 | describe('Unit Test :: generateUniqueIdentifier', () => {
74 | it('should generate a Unique Identifier', done => {
75 | done();
76 | });
77 | });
78 | });
79 |
--------------------------------------------------------------------------------
/src/jobqueue.js:
--------------------------------------------------------------------------------
1 | const Rx = require('rxjs');
2 | const hash = require('object-hash');
3 |
4 | class JobQueue {
5 | constructor() {
6 | this.jobQueue = [];
7 | this.watchdogs = {};
8 | }
9 |
10 | addJob(job) {
11 | this.jobQueue.push(job);
12 | }
13 |
14 | takeJob() {
15 | return this.jobQueue.splice(0,1)[0];
16 | }
17 |
18 | removeJob(attribute, value){
19 | for(let i = this.jobQueue.length-1; i >= 0; --i){
20 | if(this.jobQueue[i][attribute] === value){
21 | this.jobQueue.splice(i, 1);
22 | }
23 | }
24 | return;
25 | }
26 |
27 | getJobs() {
28 | return this.jobQueue;
29 | }
30 |
31 | countJobs() {
32 | return this.jobQueue.length;
33 | }
34 |
35 | addObservable(name, callback, errCallback, completeCallback, interval = 100) {
36 | if(!this.watchdogs[name]) {
37 | let subscribeCallback = () => {
38 | if(this.jobQueue.length > 0) {
39 | let currJob = this.takeJob();
40 | callback(currJob);
41 | if(currJob.loopback) {
42 | this.addJob(currJob);
43 | }
44 | }
45 | }
46 | this.watchdogs[name] = new Rx.Observable.interval(interval);
47 | this.watchdogs[name].subscribe(subscribeCallback, errCallback, completeCallback);
48 | }
49 | return this.watchdogs[name];
50 | }
51 |
52 | getObervables() {
53 | return this.watchdogs;
54 | }
55 |
56 | countObservables() {
57 | return Object.keys(this.watchdogs).length;
58 | }
59 | }
60 |
61 | class Job {
62 | constructor(pName, pTask, pCallback, pIdentifier, pLoopback) {
63 | this.name = pName;
64 | this.storedTask = pTask;
65 | this.task = (...args) => {
66 | let result = this.storedTask(...args);
67 | if(this.diffResult(result, this.lastResult)) {
68 | this.callback(result);
69 | this.lastResult = hash(sortObject(result));
70 | }
71 | this.numPolls++;
72 | return result;
73 | };
74 | this.callback = pCallback;
75 | this.numPolls = 0;
76 | this.identifier = pIdentifier;
77 | this.loopback = (pLoopback !== undefined ? pLoopback : false);
78 | this.lastResult;
79 | }
80 |
81 | getName() {
82 | return this.name;
83 | }
84 |
85 | runTask(...args) {
86 | return this.task(...args);
87 | }
88 |
89 | getTask() {
90 | return this.task;
91 | }
92 |
93 | getNumPolls() {
94 | return this.numPolls;
95 | }
96 |
97 | diffResult(newObject, lastHash) {
98 | if(this.numPolls < 1) {
99 | this.lastResult = hash(sortObject(newObject));
100 | return false;
101 | }
102 | return hash(sortObject(newObject)) !== this.lastResult;
103 | }
104 | }
105 |
106 | // Private
107 | function sortObject(object) {
108 | let sortedObj = {};
109 | let keys = Object.keys(object);
110 | keys.sort(function(key1, key2) {
111 | key1 = key1.toLowerCase(), key2 = key2.toLowerCase();
112 | if(key1 < key2) return -1;
113 | if(key1 > key2) return 1;
114 | return 0;
115 | });
116 | for(let index in keys) {
117 | let key = keys[index];
118 | if(typeof object[key] == 'object' && !(object[key] instanceof Array)) {
119 | sortedObj[key] = sortObject(object[key]);
120 | } else {
121 | sortedObj[key] = object[key];
122 | }
123 | }
124 | return sortedObj;
125 | }
126 |
127 | module.exports = { JobQueue, Job };
128 |
--------------------------------------------------------------------------------
/experimentation/server.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var graphqlHTTP = require('express-graphql');
3 | var app = express();
4 | var server = require('http').Server(app);
5 | var { buildSchema } = require('graphql');
6 | var { parseSchema, registerResolver, registerType, getRoot } = require('../src/subql.js');
7 | var { setup } = require('../src/sockets.js');
8 | var clientSchema = `
9 | input MessageInput {
10 | content: String
11 | author: String
12 | }
13 |
14 | type Message {
15 | id: ID!
16 | content: String
17 | author: String
18 | date: Date
19 | }
20 |
21 | type Date{
22 | day: Int
23 | random: String
24 | }
25 | type Query {
26 | getMessage(id: ID!): Message
27 | }
28 |
29 | type Mutation {
30 | createMessage(input: MessageInput): Message
31 | updateMessage(id: ID!, input: MessageInput): Message
32 | }
33 | `;
34 | parseSchema(clientSchema);
35 |
36 | // Construct a schema, using GraphQL schema language
37 | var schema = buildSchema(clientSchema);
38 |
39 | // If Message had any complex fields, we'd put them on this object.
40 | class Message {
41 | constructor(id, {content, author}) {
42 | this.id = id;
43 | this.content = content;
44 | this.author = author;
45 | this.date = new Date(1);
46 | }
47 | }
48 | class Date {
49 | constructor(day){
50 | this.day = day;
51 | this.random = 'alksfjasdhfjkashfdk';
52 | }
53 | }
54 | registerType(Message, 'id', 'author');
55 | registerType(Date, '');
56 |
57 | // Maps username to content
58 | var fakeDatabase = {
59 | 0 : {
60 | content: "cesar is cool",
61 | author: "dean"
62 | }
63 | };
64 |
65 | // var root = {
66 | // getMessage: function ({id}) {
67 | // if (!fakeDatabase[id]) {
68 | // throw new Error('no message exists with id ' + id);
69 | // }
70 | // return new Message(id, fakeDatabase[id]);
71 | // },
72 | // createMessage: function ({input}) {
73 | // // Create a random id for our "database".
74 | // var id = require('crypto').randomBytes(10).toString('hex');
75 |
76 | // fakeDatabase[id] = input;
77 | // return new Message(id, input);
78 | // },
79 | // updateMessage: function ({id, input}) {
80 | // if (!fakeDatabase[id]) {
81 | // throw new Error('no message exists with id ' + id);
82 | // }
83 | // // This replaces all old data, but some apps might want partial update.
84 | // fakeDatabase[id] = input;
85 | // return new Message(id, input);
86 | // },
87 | // }
88 |
89 | function getMessage({id}) {
90 | if (!fakeDatabase[id]) {
91 | throw new Error('no message exists with id ' + id);
92 | }
93 | return new Message(id, fakeDatabase[id]);
94 | }
95 | function createMessage({input}) {
96 | var id = require('crypto').randomBytes(10).toString('hex');
97 |
98 | fakeDatabase[id] = input;
99 | fakeDatabase[id].date = new Date(1);
100 | return new Message(id, input);
101 | }
102 | function updateMessage({id, input}) {
103 | if (!fakeDatabase[id]) {
104 | throw new Error('no message exists with id ' + id);
105 | }
106 | // This replaces all old data, but some apps might want partial update.
107 | fakeDatabase[id] = input;
108 | return new Message(id, input);
109 | }
110 | registerResolver(getMessage, createMessage, updateMessage);
111 | var root = getRoot();
112 |
113 | app.use('/graphql', graphqlHTTP({
114 | schema: schema,
115 | rootValue: root,
116 | graphiql: true,
117 | }));
118 |
119 | setup(server);
120 |
121 | app.get('/', (req, res) => {
122 | res.sendFile(__dirname + '/index.html')
123 | })
124 | app.get('/sockets.js', (req, res) => {
125 | res.sendFile(__dirname + '/sockets.js')
126 | })
127 |
128 | server.listen(4000, () => {
129 | console.log('Running a GraphQL API server at localhost:4000/graphql');
130 | });
--------------------------------------------------------------------------------
/experimentation/jobqueueserver.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var graphqlHTTP = require('express-graphql');
3 | var app = express();
4 | var server = require('http').Server(app);
5 | var { buildSchema } = require('graphql');
6 | var { parseSchema, registerResolver, registerType, getRoot } = require('../src/subql.js');
7 | var { setup } = require('../src/sockets.js');
8 |
9 | parseSchema(`
10 | input MessageInput {
11 | content: String
12 | author: String
13 | }
14 |
15 | type Message {
16 | id: ID!
17 | content: String
18 | author: String
19 | date: Date
20 | }
21 |
22 | type Date{
23 | month: Int
24 | day: Int
25 | year: Int
26 | }
27 |
28 | type Query {
29 | getMessage(id: ID!): Message
30 | getMessages: [Message]
31 | }
32 |
33 | type Mutation {
34 | createMessage(input: MessageInput): Message
35 | updateMessage(id: ID!, input: MessageInput): Message
36 | }
37 | `);
38 | //(id: ID!, test: String, another: String, something: String)
39 | // Construct a schema, using GraphQL schema language
40 | var schema = buildSchema(`
41 | input MessageInput {
42 | content: String
43 | author: String
44 | }
45 |
46 | type Message {
47 | id: ID!
48 | content: String
49 | author: String
50 | date: Date
51 | }
52 |
53 | type Date{
54 | month: Int
55 | day: Int
56 | year: Int
57 | }
58 |
59 | type Query {
60 | getMessage(id: ID!): Message
61 | getMessages: [Message]
62 | }
63 |
64 | type Mutation {
65 | createMessage(input: MessageInput): Message
66 | updateMessage(id: ID!, input: MessageInput): Message
67 | }
68 | `);
69 | //(id: ID!)
70 | // If Message had any complex fields, we'd put them on this object.
71 | class Message {
72 | constructor(id, {content, author}) {
73 | this.id = id;
74 | this.content = content;
75 | this.author = author;
76 | this.date = new Date(Math.floor(Math.random() * 12), Math.floor(Math.random() * 30), Math.floor(Math.random() * 3000));
77 | }
78 | }
79 | class Date {
80 | constructor(month, day, year) {
81 | this.month = month;
82 | this.day = day;
83 | this.year = year;
84 | }
85 | }
86 |
87 | registerType(Message, 'id', 'author');
88 | registerType(Date, '')
89 | // Maps username to content
90 | var fakeDatabase = {
91 | 0 : {
92 | content: "cesar is cool",
93 | author: "dean",
94 | date: {
95 | month: 12,
96 | day: 13,
97 | year: 2016
98 | }
99 | }
100 | };
101 |
102 | // var root = {
103 | // getMessage: function ({id}) {
104 | // if (!fakeDatabase[id]) {
105 | // throw new Error('no message exists with id ' + id);
106 | // }
107 | // return new Message(id, fakeDatabase[id]);
108 | // },
109 | // createMessage: function ({input}) {
110 | // // Create a random id for our "database".
111 | // var id = require('crypto').randomBytes(10).toString('hex');
112 |
113 | // fakeDatabase[id] = input;
114 | // return new Message(id, input);
115 | // },
116 | // updateMessage: function ({id, input}) {
117 | // if (!fakeDatabase[id]) {
118 | // throw new Error('no message exists with id ' + id);
119 | // }
120 | // // This replaces all old data, but some apps might want partial update.
121 | // fakeDatabase[id] = input;
122 | // return new Message(id, input);
123 | // },
124 | // }
125 |
126 | function getMessage({id}) {
127 | if (!fakeDatabase[id]) {
128 | throw new Error('no message exists with id ' + id);
129 | }
130 | return new Message(id, fakeDatabase[id]);
131 | }
132 | function createMessage({input}) {
133 | var id = require('crypto').randomBytes(10).toString('hex');
134 |
135 | fakeDatabase[id] = input;
136 | return new Message(id, input);
137 | }
138 | function updateMessage({id, input}) {
139 | if (!fakeDatabase[id]) {
140 | throw new Error('no message exists with id ' + id);
141 | }
142 | // This replaces all old data, but some apps might want partial update.
143 | fakeDatabase[id] = input;
144 | return new Message(id, input);
145 | }
146 | //getMessages(id: ID!, test: String, another: String, something: String): [Message]
147 | function getMessages() {
148 | // {id, test, another, something}
149 | // console.log(`Arguments to getMessages\nid: ${id}\ntest: ${test}\nanother: ${another}\nsomething: ${something}`);
150 | return Object.keys(fakeDatabase).reduce((acc, curr) =>{
151 | acc.push(fakeDatabase[curr]);
152 | return acc;
153 | }, []);
154 | }
155 | registerResolver(getMessage, getMessages, createMessage, updateMessage);
156 | var root = getRoot();
157 |
158 | app.use('/graphql', graphqlHTTP({
159 | schema: schema,
160 | rootValue: root,
161 | graphiql: true,
162 | }));
163 |
164 | setup(server);
165 |
166 | app.get('/', (req, res) => {
167 | res.sendFile(__dirname + '/index.html')
168 | })
169 | app.get('/sockets.js', (req, res) => {
170 | res.sendFile(__dirname + '/sockets.js')
171 | })
172 |
173 | server.listen(4000, () => {
174 | console.log('Running a GraphQL API server at localhost:4000/graphql');
175 | });
--------------------------------------------------------------------------------
/src/subql.js:
--------------------------------------------------------------------------------
1 | const graphql = require('graphql');
2 | const { connected } = require('./socketdata.js');
3 | const {JobQueue, Job} = require('./jobqueue.js');
4 |
5 | const db = {};
6 | const mroot = {};
7 | const otypes = {};
8 | const operations = {};
9 | var storedSchema = '';
10 | var jobQueue = new JobQueue();
11 | jobQueue.addObservable("observable1", (job) => job.runTask(), (err) => console.log(err), () => console.log('complete'));
12 | jobQueue.addObservable("observable2", (job) => job.runTask(), (err) => console.log(err), () => console.log('complete'));
13 | jobQueue.addObservable("observable3", (job) => job.runTask(), (err) => console.log(err), () => console.log('complete'));
14 | jobQueue.addObservable("observable4", (job) => job.runTask(), (err) => console.log(err), () => console.log('complete'));
15 |
16 | function parseSchema(schema) {
17 | if (!schema) {
18 | throw new Error('parseSchema :: parseSchema must take in a schema string');
19 | }
20 | storedSchema = schema;
21 | let schemaSource = new graphql.Source(schema);
22 | let parsedSchema = graphql.parse(schema);
23 | parsedSchema.definitions.forEach((ele) => {
24 | if (ele.name.value === 'Query' || ele.name.value === 'Mutation') {
25 | ele.fields.forEach((field) => {
26 | operations[field.name.value] = {
27 | name: field.name.value,
28 | type: ele.name.value,
29 | // for List Types, field.type.kind defines a list type and field.type.type.kind defines the named type
30 | value: field.type.kind === "ListType" ? field.type.type.name.value : field.type.name.value,
31 | kind: field.type.kind
32 | }
33 | });
34 | }
35 | });
36 | }
37 |
38 | function registerType(classFn, ...uniqKeys) {
39 | if(typeof classFn !== 'function') {
40 | throw new Error('registerType :: registerType must take in a constructor function as first argument');
41 | }
42 | if(!uniqKeys) {
43 | throw new Error('registerType :: registerType did not recieve any keys as arguments');
44 | }
45 | otypes[classFn.name] = {
46 | name: classFn.name,
47 | classType: classFn,
48 | keys: uniqKeys,
49 | };
50 | }
51 |
52 | function registerResolver(...rootFn) {
53 | if(!rootFn) {
54 | throw new Error('registerResolver :: registerResolver must take at least one resolver function.');
55 | }
56 | rootFn.forEach((fn) => {
57 | if(fn.name.length <= 0) {
58 | throw new Error('registerResolver :: registerResolver can not take anonymous functions as arguments');
59 | }
60 | mroot[fn.name] = wrapResolver(fn);
61 | });
62 | }
63 |
64 | /**
65 | * wrapResolver will add the trigger functionality to notify clients
66 | * for operations of type Mutation and not ListTypes
67 | */
68 | function wrapResolver(fn) {
69 | if(operations[fn.name].type === 'Mutation' && operations[fn.name].kind !== 'ListType') {
70 | return function (...args) {
71 | let ret = fn(...args);
72 | triggerType(ret.constructor.name, ret);
73 | return ret;
74 | }
75 | } else {
76 | return fn;
77 | }
78 | }
79 |
80 | function getSchema(){
81 | return storedSchema;
82 | }
83 |
84 | function getRoot() {
85 | return mroot;
86 | }
87 |
88 | /**
89 | * handleSubscribe takes a query string and a socket it
90 | * It will store the proper information necesary to allow mutations to
91 | * use the socketid to notify clients about updates to data
92 | */
93 | function handleSubscribe(query, socketid) {
94 | const root = Object.assign({}, getRoot());
95 | const parseQuery = graphql.parse(query.query);
96 | let queryOperations = getOperationNames(parseQuery);
97 | connected[socketid].query = query.query;
98 | connected[socketid].operationFields = findFields(parseQuery, {});
99 |
100 |
101 | queryOperations.forEach((resolverName) => {
102 | if(operations[resolverName].kind === 'ListType') {
103 | let queries = parseQuery.definitions.reduce((acc, curr) => {
104 | return curr.operation === 'query' ? curr : acc;
105 | }, { selectionSet: { selections: [] } });
106 | let currentSelection = queries.selectionSet.selections.reduce((acc, curr) => {
107 | return curr.name.value === resolverName ? curr : acc;
108 | }, {});
109 | let inputs = currentSelection.arguments.reduce((acc, curr) => {
110 | acc[curr.name.value] = curr.value.value;
111 | return acc;
112 | }, {});
113 | jobQueue.addJob(new Job(
114 | resolverName + JSON.stringify(inputs),
115 | () => root[resolverName](inputs),
116 | (result) => {
117 | let mutateddata = { data: {} };
118 | mutateddata.data[resolverName] = result.map(val => queryFilter(val, connected[socketid]));
119 | return connected[socketid] !== undefined
120 | ? connected[socketid].socket.emit(socketid, mutateddata)
121 | : console.log(`[Job] :: client has disconnected`)},
122 | socketid,
123 | true
124 | ));
125 | } else if(operations[resolverName].type === 'Query') {
126 | let oldResolver = root[resolverName];
127 | root[resolverName] = function (...args) {
128 | let ret = oldResolver(...args);
129 | let uniqIdentifier = generateUniqueIdentifier(operations[resolverName].value, ret);
130 | db[uniqIdentifier] = !db[uniqIdentifier] ? [socketid] : [...db[uniqIdentifier], socketid];
131 | return ret;
132 | }
133 | }
134 | });
135 |
136 | graphql.graphql(
137 | graphql.buildSchema(storedSchema),
138 | query.query,
139 | root
140 | ).then((result) => {
141 | if(connected[socketid]){
142 | connected[socketid].socket.emit(socketid, result);
143 | }else{
144 | // client has disconnected.
145 | // TODO add in logic for removing data about disconnected client
146 | }
147 | });
148 | }
149 |
150 | function getOperationNames(parsedQuery) {
151 | let results = [];
152 | parsedQuery.definitions.forEach( (definition) => {
153 | if(definition.operation === 'query'){
154 | definition.selectionSet.selections.forEach((curr) => {
155 | results.push(curr.name.value);
156 | });
157 | }
158 | });
159 | return results;
160 | }
161 |
162 | /**
163 | * Traverses through the parsed query and retrieves all the resolver names (fields)
164 | */
165 | function findFields(parsedQuery, store) {
166 | let collection = parsedQuery.definitions[0].selectionSet.selections;
167 | function findFieldshelper(val, store) {
168 | store[val.name.value] = [];
169 | val.selectionSet.selections.forEach(field => {
170 | if (field.selectionSet) {
171 | store[val.name.value].push(findFieldshelper(field, {}));
172 | } else {
173 | store[val.name.value].push(field.name.value);
174 | }
175 | });
176 | return store;
177 | }
178 | collection.forEach((val) => {
179 | findFieldshelper(val, store);
180 | });
181 | return store;
182 | }
183 |
184 | function handleDisconnect(socketid) {
185 | jobQueue.removeJob('identifier', socketid);
186 | Object.keys(db).forEach((uniqIdentifier) => {
187 | let socketIndex = db[uniqIdentifier].indexOf(socketid);
188 | if(socketIndex >= 0) {
189 | db[uniqIdentifier].splice(socketIndex, 1);
190 | }
191 | });
192 | delete connected[socketid];
193 | }
194 |
195 | function triggerType(typename, resolverResult) {
196 | if(otypes[typename] === undefined) {
197 | throw new Error(`triggerType :: There exists no registered type named ${typename}`);
198 | }
199 | let uniqIdentifier = generateUniqueIdentifier(typename, resolverResult);
200 | if(db[uniqIdentifier] !== undefined) {
201 | db[uniqIdentifier].forEach((socket) => {
202 | if (connected[socket] !== undefined) {
203 | connected[socket].socket.emit(socket, queryFilter(resolverResult, connected[socket]));
204 | }
205 | });
206 | }
207 | };
208 |
209 | function queryFilter(resolverResult, clientObj) {
210 | let {list, matchedResolver} = determineList_Resolver(resolverResult, clientObj);
211 | let retObjectTemplate;
212 | let retObjFill;
213 | if (list) {
214 | retObjectTemplate = {};
215 | retObjFill = retObjectTemplate;
216 | } else {
217 | retObjectTemplate = { data: {} };
218 | retObjectTemplate.data[matchedResolver] = {};
219 | retObjFill = retObjectTemplate.data[matchedResolver];
220 | }
221 | let fields = clientObj.operationFields[matchedResolver];
222 | nestedQueryHelper(fields, resolverResult, retObjFill);
223 | return retObjectTemplate;
224 | }
225 | // function name can be changed to be more relavent
226 | function determineList_Resolver(resolverResult, clientObject) {
227 | let typeOfObj = resolverResult.constructor.name;
228 | let resolverNames = Object.keys(clientObject.operationFields);
229 | let list = false;
230 | let matchedResolver;
231 | resolverNames.forEach((resolver) => {
232 | if (operations[resolver].value === typeOfObj && operations[resolver].kind === "NamedType") {
233 | matchedResolver = resolver;
234 | } else if(operations[resolver].value === typeOfObj){
235 | matchedResolver = resolver;
236 | list = true;
237 | }
238 | });
239 | return { list, matchedResolver };
240 | }
241 | // name may need to be changed since it works in general
242 | // handles the entire query filtering process
243 | function nestedQueryHelper(fieldArray, resolverObj, resultObj) { //TODO can we possibly refactor with similar code in query filter
244 | fieldArray.forEach((key) => {
245 | if(typeof key === 'object') {
246 | let fieldKey = Object.keys(key)[0];
247 | if (!Array.isArray(resolverObj[fieldKey])) {
248 | resultObj[fieldKey] = nestedQueryHelper(key[fieldKey], resolverObj[fieldKey], {});
249 | } else {
250 | resultObj[fieldKey] = resolverObj[fieldKey].map(ele => nestedQueryHelper(key[fieldKey], ele, {}));
251 | }
252 | } else {
253 | resultObj[key] = resolverObj[key];
254 | }
255 | });
256 | return resultObj;
257 | }
258 |
259 | function generateUniqueIdentifier(typename, resolverResult) {
260 | if(otypes[typename] === undefined) {
261 | throw new Error(`generateUniqueIdentifier :: There exists no registered type named ${typename}`);
262 | }
263 | let uniqKeys = otypes[typename].keys;
264 | return typename + uniqKeys.reduce((acc, curr) => {
265 | return acc + curr + resolverResult[curr];
266 | }, '');
267 | }
268 |
269 | module.exports = {
270 | registerResolver,
271 | getRoot,
272 | getSchema,
273 | registerType,
274 | parseSchema,
275 | handleSubscribe,
276 | handleDisconnect,
277 | triggerType
278 | };
--------------------------------------------------------------------------------