Commit f8464e2c authored by Joshua Stein's avatar Joshua Stein
Browse files

RH

parents
/* @flow */
import ConversationV1 from 'watson-developer-cloud/conversation/v1';
import config from '../config';
/**
* Initialize Watson Conversation SDK.
*/
const conversationSDK = new ConversationV1({
username: '5ddce1ff-8260-4211-8add-35162f36e385', // config.watson.conversation.username,
password: 'GXo0UTq4wNOx',
workspace: '6eba9882-5164-45f4-8ecd-fd3bb5572104',
version_date: '2017-05-26',
});
/**
* Conversation class that holds all functions about Watson Conversation.
* Add more functions that leverage the Watson Conversation SDK here.
*/
class Conversation {
/**
* This synchronous function leverages the SDK to send a
* message to Watson Conversation.
* It returns a JSON object from Watson Conversation
* @param {string} text
* @param {Object=} context
* @returns Promise
*/
message = (text: string, context?: Object): Promise<any> => {
const payload = {
workspace: '6eba9882-5164-45f4-8ecd-fd3bb5572103',
input: {
text,
},
context,
};
return new Promise((resolve, reject) =>
conversationSDK.message(payload, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
}),
);
};
/**
* This synchronous function leverages the Watson Conversation SDK
* to obtain a JSON representation of your Watson Service.
* @returns Promise
*/
static getWorkspace = (): Promise<any> => {
const params = {
workspace_id: config.watson.conversation.workspace,
export: true,
};
return new Promise((resolve, reject) =>
conversationSDK.getWorkspace(params, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
}),
);
};
}
export default Conversation;
// eslint-disable global-require
const fs = require('fs');
const path = require('path');
const winston = require('winston');
const WinstonRotateFile = require('winston-daily-rotate-file');
const logDirectory = '../logs';
const logFilename = path.resolve(logDirectory, `${logDirectory}/-logfile.log`);
const timestampFormat = () => new Date().toLocaleTimeString();
const prettyprintFormat = obj => JSON.stringify(obj, null, 2);
if (!fs.existsSync(logDirectory)) {
fs.mkdirSync(logDirectory);
}
const logger = new winston.Logger({
transports: [
new winston.transports.Console({
timestamp: timestampFormat,
colorize: true,
level: 'debug',
prettyPrint: prettyprintFormat,
}),
new WinstonRotateFile({
filename: logFilename,
timestamp: timestampFormat,
datePattern: 'yyyy-MM-dd',
prepend: true,
level: 'info',
json: false,
prettyprint: prettyprintFormat,
}),
],
});
logger.stream = {
/* eslint-disable no-unused-vars */
write: (message, encoding) => {
logger.info(message);
},
};
module.exports = logger;
/* @flow */
import { Router } from 'express';
import logger from './logger';
// import ConversationV1 from 'watson-developer-cloud';
const Watson = require('watson-developer-cloud');
const conversationSDK = new Watson.ConversationV1({
username: 'MISSING VALUE',
password: 'MISSING VALUE',
workspace: 'MISSING VALUE',
version_date: '2017-05-26',
});
logger.info(conversationSDK);
const router = new Router();
router.post('/conversation', (req, res) => {
/*
==========================^^^=========================
ROUTING CODE GOES HERE
==========================vvv=========================
*/
logger.info(req);
logger.info(res);
});
export default router;
/* @flow */
/* eslint-disable no-console, no-shadow */
import app from './app';
// const app = require('./app');
import config from './config';
// Launch Node.js server
const server = app.listen(config.port, config.host, () => {
console.log(
`Node.js server is listening on http://${config.host}:${config.port}/`,
);
});
// Shutdown Node.js app gracefully
function handleExit(options, err) {
if (options.cleanup) {
const actions = [server.close];
actions.forEach((close, i) => {
try {
close(() => {
if (i === actions.length - 1) process.exit();
});
} catch (err) {
if (i === actions.length - 1) process.exit();
}
});
}
if (err) console.log(err.stack);
if (options.exit) process.exit();
}
process.on('exit', handleExit.bind(null, { cleanup: true }));
process.on('SIGINT', handleExit.bind(null, { exit: true }));
process.on('SIGTERM', handleExit.bind(null, { exit: true }));
process.on('uncaughtException', handleExit.bind(null, { exit: true }));
{
"rules": {
"global-require": "off",
"no-console": "off",
"import/no-extraneous-dependencies": ["error", { "devDependencies": true }]
}
}
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const del = require('del');
const babel = require('babel-core');
const chokidar = require('chokidar');
const task = require('./task');
const delay100ms = (timeout => callback => {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(callback, 100); // eslint-disable-line no-param-reassign
})();
module.exports = task(
'build',
({ watch = false, onComplete } = {}) =>
new Promise(resolve => {
let ready = false;
// Clean up the output directory
del.sync(['build/**', '!build'], { dot: true });
let watcher = chokidar.watch(['src', 'package.json'], {});
watcher.on('all', (event, src) => {
// Reload the app if package.json (in watch mode)
if (src === 'package.json' || src === 'package.lock.json') {
if (ready && onComplete) delay100ms(onComplete);
return;
}
if (
path.basename(src)[0] === '.' ||
src.includes('__tests__') ||
src.endsWith('.test.js') ||
src.includes('__mocks__')
) {
return;
}
// Get destination file name, e.g. src/app.js (src) -> build/app.js (dest)
const dest = src.startsWith('src')
? `build/${path.relative('src', src)}`
: `build/${src}`;
try {
switch (event) {
// Create a directory if it doesn't exist
case 'addDir':
if (src.startsWith('src') && !fs.existsSync(dest))
fs.mkdirSync(dest);
if (ready && onComplete) onComplete();
break;
// Create or update a file inside the output (build) folder
case 'add':
case 'change':
if (src.startsWith('src') && src.endsWith('.js')) {
const { code, map } = babel.transformFileSync(src, {
sourceMaps: true,
sourceFileName: path.relative(
path.dirname(`build${src.substr(3)}`),
src,
),
});
// Enable source maps
const data =
(src === 'src/server.js'
? "require('source-map-support').install(); "
: '') +
code +
(map
? `\n//# sourceMappingURL=${path.basename(src)}.map\n`
: '');
fs.writeFileSync(dest, data, 'utf8');
console.log(src, '->', dest);
if (map)
fs.writeFileSync(`${dest}.map`, JSON.stringify(map), 'utf8');
} else if (src.startsWith('src')) {
const data = fs.readFileSync(src, 'utf8');
fs.writeFileSync(dest, data, 'utf8');
console.log(src, '->', dest);
}
if (ready && onComplete) delay100ms(onComplete);
break;
// Remove directory if it was removed from the source folder
case 'unlinkDir':
if (fs.existsSync(dest)) fs.rmdirSync(dest);
if (ready && onComplete) onComplete();
break;
default:
// Skip
}
} catch (err) {
console.log(err.message);
}
});
watcher.on('ready', () => {
ready = true;
if (onComplete) onComplete();
if (!watch) watcher.close();
resolve();
});
function cleanup() {
if (watcher) {
watcher.close();
watcher = null;
}
}
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
process.on('exit', cleanup);
}),
);
/* eslint-disable no-undef */
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
#!/usr/bin/env node
const cp = require('child_process');
const pkg = require('../package.json');
const task = require('./task');
let server;
let debugPort = '9230';
const serverQueue = [];
const isDebug = process.execArgv.some(x => x.startsWith('--inspect'));
// Gracefull shutdown
process.once('cleanup', () => {
if (server) {
server.addListener('exit', () => process.exit());
server.kill('SIGTERM');
serverQueue.forEach(x => x.kill());
} else {
process.exit();
}
});
process.on('SIGINT', () => process.emit('cleanup'));
process.on('SIGTERM', () => process.emit('cleanup'));
// Ensure that Node.js modules were installed,
// at least those required to build the app
cp.spawnSync('yarn', ['install', '--no-progress'], { stdio: 'inherit' });
const build = require('./build');
// Launch `node build/server.js` on a background thread
function spawnServer() {
return cp.spawn(
'node',
[
// Pre-load application dependencies to improve "hot reload" restart time
...Object.keys(pkg.dependencies).reduce(
(requires, val) => requires.concat(['--require', val]),
[],
),
// If the parent Node.js process is running in debug (inspect) mode,
// launch a debugger for Express.js app on the next port
...process.execArgv.map(arg => {
if (arg.startsWith('--inspect')) {
const match = arg.match(/^--inspect=(\S+:|)(\d+)$/);
if (match) debugPort = Number(match[2]) + 1;
return `--inspect=${match ? match[1] : '0.0.0.0:'}${debugPort}`;
}
return arg;
}),
'--no-lazy',
// Enable "hot reload", it only works when debugger is off
...(isDebug
? ['./server.js']
: [
'--eval',
'process.stdin.on("data", data => { if (data.toString() === "load") require("./server.js"); });',
]),
],
{ cwd: './build', stdio: ['pipe', 'inherit', 'inherit'], timeout: 3000 },
);
}
module.exports = task('run', () =>
Promise.resolve()
// Compile and launch the app in watch mode, restart it after each rebuild
.then(() =>
build({
watch: true,
onComplete() {
if (isDebug) {
if (server) {
server.on('exit', () => {
server = spawnServer();
});
server.kill('SIGTERM');
} else {
server = spawnServer();
}
} else {
if (server) server.kill('SIGTERM');
server = serverQueue.splice(0, 1)[0] || spawnServer();
server.stdin.write('load'); // this works faster than IPC
if (server)
while (serverQueue.length < 3) serverQueue.push(spawnServer());
}
},
}),
)
// Resolve the promise on exit
.then(
() =>
new Promise(resolve => {
process.once('exit', () => {
if (server) server.kill();
resolve();
});
}),
),
);
/*
* Minimalistic script runner. Usage example:
*
* node tools/run
* Starting 'run'...
* Finished 'run' in 25ms
*/
function run(task, action, ...args) {
const command = process.argv[2];
const taskName =
command && !command.startsWith('-') ? `${task}-${command}` : task;
const start = new Date();
process.stdout.write(`Starting '${taskName}'...\n`);
return Promise.resolve()
.then(() => action(...args))
.then(
() => {
process.stdout.write(
`Finished '${taskName}' after ${new Date().getTime() -
start.getTime()}ms\n`,
);
},
err => process.stderr.write(`${err.stack}\n`),
);
}
process.nextTick(() => require.main.exports());
module.exports = (task, action) => run.bind(undefined, task, action);
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment