Skip to content

Instantly share code, notes, and snippets.

@appwiz
Created October 9, 2018 16:07
Show Gist options
  • Save appwiz/8702ccc5121c7362e5296d4364bafadf to your computer and use it in GitHub Desktop.
Save appwiz/8702ccc5121c7362e5296d4364bafadf to your computer and use it in GitHub Desktop.
'use strict';
// CONFIG
const AppSync = {
"graphqlEndpoint": "...",
"region": "...",
"authenticationType": "API_KEY",
"apiKey": "..."
};
// POLYFILLS
global.WebSocket = require('ws');
global.window = global.window || {
setTimeout: setTimeout,
clearTimeout: clearTimeout,
WebSocket: global.WebSocket,
ArrayBuffer: global.ArrayBuffer,
addEventListener: function () { },
navigator: { onLine: true }
};
global.localStorage = {
store: {},
getItem: function (key) {
return this.store[key]
},
setItem: function (key, value) {
this.store[key] = value
},
removeItem: function (key) {
delete this.store[key]
}
};
require('es6-promise').polyfill();
require('isomorphic-fetch');
// Require AppSync module
const AUTH_TYPE = require('aws-appsync/lib/link/auth-link').AUTH_TYPE;
const AWSAppSyncClient = require('aws-appsync').default;
// INIT
// Set up AppSync client
const client = new AWSAppSyncClient({
url: AppSync.graphqlEndpoint,
region: AppSync.region,
auth: {
type: AUTH_TYPE.API_KEY,
apiKey: AppSync.apiKey
}
});
// GRAPHQL
const gql = require('graphql-tag');
const OnCommandSubscription = gql(`
subscription OnCreateCommand {
onCreateCommands2 {
__typename
command
id
timestamp
action
}
}
`);
const exec = require('child_process').exec;
// APP CODE
client.hydrated().then(function (client) {
// Now subscribe to results
const observable = client.subscribe({ query: OnCommandSubscription });
const realtimeResults = function realtimeResults(data) {
console.log('(realtime) command: ', data.data.onCreateCommands2);
let action = data.data.onCreateCommands2.action;
console.log('action: ', action);
if (action === "blue") {
exec("<command>", (err, stdout, stderr) => console.log(stdout));
} else if (action === "green") {
exec("<command>", (err, stdout, stderr) => console.log(stdout));
} else {
console.log("unknown action: ", action);
}
};
observable.subscribe({
next: realtimeResults,
complete: console.log,
error: console.log,
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment