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

RH

parents
{
"presets": [
[
"env",
{
"targets": {
"node": "current"
}
}
]
],
"plugins": [
"transform-class-properties",
"transform-export-extensions",
"transform-flow-strip-types",
"transform-object-rest-spread"
],
"retainLines": true
}
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# http://editorconfig.org
root = true
[*]
# Recommend you to keep these unchanged
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
public/*
\ No newline at end of file
const fs = require('fs');
const prettierOptions = JSON.parse(fs.readFileSync('./.prettierrc', 'utf8'));
// http://eslint.org/docs/user-guide/configuring
// https://github.com/prettier/prettier#eslint
module.exports = {
parser: 'babel-eslint',
extends: ['airbnb-base', 'prettier'],
plugins: ['flowtype', 'prettier'],
rules: {
'prettier/prettier': ['error', prettierOptions],
'flowtype/define-flow-type': 1,
"linebreak-style": 0
},
};
[ignore]
.*/build/.*
.*/config/.*
.*/coverage/.*
.*/tools/.*
[options]
esproposal.export_star_as=enable
unsafe.enable_getters_and_setters=true
\ No newline at end of file
# Include your project-specific ignores in this file
# Read about how to use .gitignore: https://help.github.com/articles/ignoring-files
build
node_modules
npm-debug.log
yarn-error.log
logs
.env
# Editors and IDEs
.vscode/*
!.vscode/snippets
!.vscode/launch.json
!.vscode/settings.json
node_modules
package.json
README.md
\ No newline at end of file
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true
}
\ No newline at end of file
# Table of Contents
- [Overview](#overview)
- [Technology Stack](#technology-stack)
- [Directory Layout](#directory-layout)
- [Quickstart](#quickstart)
- [Prerequisites](#prerequisites)
- [Getting started](#getting-started)
- [How to test](#how-to-test)
- [How to debug](#how-to-debug)
- [Deploying to IBM cloud](#deploying-to-ibm-cloud)
- [Delivery Pipeline](#delivery-pipeline)
- [API Documentation](#api-documentation)
- [Demos](#demos)
- [Reference Articles and Tutorials](#reference-articles-and-tutorials)
# Overview
The ACIT NodeJS Starter is a boilerplate and tooling application for bootstrapping [NodeJS](https://nodejs.org/en/) infrastructures with a focus on [IBM Cloud](https://www.ibm.com/cloud/) technologies. It is best suited for developing REST APIs as a stand-alone (micro)service, backing up mobile or web front-ends (See [acit-ng-seed](https://git.ng.bluemix.net/ruben.gomez/acit-ng-seed)). For more information about the ACIT, please visit [us](https://in.accenture.com/ibm/).
This project was forked and based on Kriasoft's [NodeJS API Starter Project](https://github.com/kriasoft/nodejs-api-starter)
## Technology Stack
* [NodeJS](https://nodejs.org/en/), [Yarn](https://yarnpkg.com/en/), [JavaScript](https://developer.mozilla.org/docs/Web/JavaScript),
[Babel](http://babeljs.io/),
[Flow](https://flow.org/),
[ESLint](https://eslint.org/),
[Prettier](https://prettier.io/) — Core platform and web tools
* [Express](https://expressjs.com/),
[session](https://github.com/expressjs/session), [cors](https://github.com/expressjs/cors) — Common HTTP server features.
* [Jest](http://facebook.github.io/jest/) - Unit and snapshot testing
## Directory Layout
```bash
.
├── /build/ # The compiled output (via Babel)
├── /src/ # Node.js application source files
│ ├── /__tests__/ # Application tests
│ ├── /routes/ # Express endpoints
│ ├── /app.js # Express.js application
│ ├── /config.js # Specific application configuration information
│ ├── /logger.js # Application information logger
│ ├── /router.js # Express endpoints router
│ └── /server.js # Node.js server (entry point)
├── /tools/ # Build automation scripts and utilities
├── package.json # List of project dependencies
```
# Quickstart
## Prerequisites
1) NodeJS [8.9.4](https://nodejs.org/en/download/) or above
2) [Yarn](https://yarnpkg.com/en/docs/install)
3) Highly recommended: [Visual Studio Code](https://code.visualstudio.com/) Extensions: EditorConfig, ESLint, Flow and Prettier.
## Getting started
Clone this project and host the code either on Github or IBM's Git repository
`git clone the repo'
`cd <your-project-name>`
Install dependecies.
`yarn install`
To build the project and launch a development server with hot reload.
`yarn dev`
The NodeJS server will be listening on https://localhost:3000
---
## How to test
```bash
yarn lint # Find problematic patterns in code
yarn check # Check source code for type errors
yarn test # Runs Jest on the project
```
With Visual Studio Code's debugger you can also launch Jest in debug mode with the included configuration.
For more information visit http://facebook.github.io/jest/
## How to debug
In order to run the app with V8 inspector enabled, simply run the server in debug mode `yarn run debug` and use Visual Studio Code's debugger to attach to the running process.
Pending
# Demos
[Watson Conversation Demo](https://acit-node-starter.mybluemix.net/)
# Reference Articles and Tutorials
* [Working with Delivery Pipelines](https://console.bluemix.net/docs/services/ContinuousDelivery/pipeline_working.html#pipeline-working)
* [Stop using JWT for sesstions](http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/)
([part 2](http://cryto.net/~joepie91/blog/2016/06/19/stop-using-jwt-for-sessions-part-2-why-your-solution-doesnt-work/))
by [Sven Slootweg](https://github.com/joepie91)
* [How to Safely Store Your Users' Passwords](https://paragonie.com/blog/2016/02/how-safely-store-password-in-2016) by [P.I.E.](https://paragonie.com/)
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "api",
"version": "0.0.0",
"private": true,
"engines": {
"node": "8.9.4"
},
"dependencies": {
"body-parser": "^1.18.2",
"compression": "^1.7.1",
"cookie-parser": "^1.4.3",
"cors": "^2.8.4",
"dotenv": "^5.0.0",
"express": "^4.15.5",
"fs": "0.0.1-security",
"jest": "^21.2.0",
"morgan": "^1.9.0",
"pretty-error": "^2.1.1",
"source-map-support": "^0.4.18",
"supertest": "^3.0.0",
"watson-developer-cloud": "^2.40.0",
"winston": "^2.4.0",
"winston-daily-rotate-file": "^1.7.2",
"xlsx-to-json": "^0.3.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.1",
"babel-jest": "^21.2.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-export-extensions": "^6.22.0",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.0",
"babel-preset-minify": "^0.2.0",
"babel-register": "^6.26.0",
"chokidar": "^1.7.0",
"del": "3.0.0",
"eslint": "^4.7.2",
"eslint-config-airbnb-base": "^12.0.1",
"eslint-config-prettier": "^2.6.0",
"eslint-plugin-flowtype": "^2.36.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-prettier": "^2.3.1",
"flow-bin": "^0.55.0",
"husky": "^0.14.3",
"jest-cli": "^21.2.1",
"jest-tobetype": "^1.1.0",
"lint-staged": "^4.2.3",
"prettier": "^1.7.1"
},
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/tools/jest.setup.js"
},
"lint-staged": {
"*.js": [
"eslint --fix",
"git add --force"
],
"*.{json}": [
"prettier --parser json --write",
"git add --force"
]
},
"scripts": {
"precommit": "lint-staged",
"lint": "eslint --ignore-path .gitignore --ignore-pattern \"!**/.*\" .",
"fix": "eslint --ignore-path .gitignore --ignore-pattern \"!**/.*\" --fix .",
"check": "flow check",
"test": "jest",
"test-watch": "jest --watch",
"build": "node tools/build.js",
"build-watch": "node tools/build.js --watch",
"debug": "node -r dotenv/config --inspect=0.0.0.0:9229 tools/run.js",
"dev": "node -r dotenv/config tools/run.js",
"start": "node build/server.js"
}
}
<DOCTYPE html/>
<head>
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js'> </script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Liquid Automations</h1>
<div id="maindiv" ng-app="app" ng-controller="angularController">
<button type="button" ng-click="testfunc()">List Workspaces</button>
<p>{{output}} </p>
<input type="text" ng-model="inputText">
<button type="button" ng-click="getConvResponse()">Submit</button>
<p>{{convResponse}} </p>
<button type="button" ng-click="expressBtnTest()">Submit</button>
<p>{{expResponse}} </p>
</div>
</body>
<script>
var app = angular.module("app", []);
app.controller("angularController", function ($scope, $http) {
$scope.testfunc = function () {
$http.get("/workspaces").then(function (response, err) {
$scope.output = response.data;
});
}
$scope.getConvResponse = function () {
// console.log($scope.inputText);
$http.post("/conversationMessage", { data: $scope.inputText }).then(function (response, err) {
// console.log(response);
$scope.convResponse = response.data;
})
}
});
/*
const getString = function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/banterlink');
xhr.onload = function () {
if (xhr.status === 200) {
//alert('response ' + xhr.responseText);
document.getElementById("output").innerHTML = xhr.responseText;
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
}; */
</script>
body {
background-color: rgb(41, 170, 48);
}
h1 {
color: white;
align-content: center;
}
#maindiv {
margin: 0 auto;
}
/* eslint-env jest */
test('test to confirm jest is working', () => {
expect(1).toBe(1);
});
import logger from '../logger';
const NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
username: '42855eef-74ae-4064-8a13-9f4fdfaf424f',
password: 'Pdp6peE5vPLs',
version_date: '2017-02-27',
});
const parameters = {
text:
'Leonardo DiCaprio won Best Actor in a Leading Role for his performance. Max Thorpe was awarded the fastest award',
features: {
entities: {
emotion: true,
sentiment: true,
limit: 2,
},
keywords: {
emotion: true,
sentiment: true,
limit: 2,
},
relations: {},
},
};
naturalLanguageUnderstanding.analyze(parameters, (err, response) => {
if (err) logger.info('error:', err);
else logger.info(JSON.stringify(response, null, 2));
});
/* @flow */
import { $Request, $Response } from 'express';
import logger from '../logger';
import Conversation from '../lib/conversation';
const conversation = new Conversation();
/**
* This function handles the logic for the chatbot endpoint.
* It returns the Watson Conversation response to the client.
* @param {$Request} req
* @param {$Response} res
*/
const message = async (req: $Request, res: $Response) => {
let response: Object = {};
// logger.info(req);
try {
const { body: { input: { text } } } = req;
const { body: { context } } = req;
try {
logger.debug(`Sending text:`, text, `and context\n`, context);
response = await conversation.message(text, context);
logger.debug(`Response received: \n`, response);
} catch (error) {
logger.error(
`There was an error retrieving a response from Watson Conversation`,
error,
);
}
} catch (error) {
logger.error(`There was an error parsing the request from client`, error);
}
res.send(response);
};
export default message;
import logger from './logger';
const watson = require('watson-developer-cloud');
const conversation = watson.conversation({
username: '5ddce1ff-8260-4211-8add-35162f36e385',
password: 'GXo0UTq4wNOx',
version: 'v1',
version_date: '2017-05-26',
});
conversation.message(
{
workspace_id: '22bdd246-5bbb-4746-b9cc-845ac12bd779',
input: { text: 'Hello' },
},
(err, response) => {
if (err) logger.info('error:', err);
else logger.info(JSON.stringify(response, null, 2));
},
);
/* @flow */
import path from 'path';
import express from 'express';
import cors from 'cors';
import compression from 'compression';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import PrettyError from 'pretty-error';
import morgan from 'morgan';
import router from './router';
import logger from './logger';
const app = express();
app.use(morgan('combined', { stream: logger.stream }));
app.use(express.static(path.resolve(__dirname, '../public/')));
app.set('trust proxy', 'loopback');
/*
const corsOptions = {
origin: 'https://appstelfrontend.eu-gb.mybluemix.net/',
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
}; */
app.use(
cors({
origin(origin, next) {
const whitelist = process.env.CORS_ORIGIN
? process.env.CORS_ORIGIN.split(',')
: [
'http://appstelfrontend.eu-gb.mybluemix.net',
'https://appstelfrontend.eu-gb.mybluemix.net',
'http://localhost:9000',
'http://localhost:4200',
];
next(null, whitelist.includes(origin));
},
credentials: true,
}),
);
// app.use(cors(corsOptions));
app.use(compression());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(router);
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
pe.withoutColors(); // So that logfile output is clean.
pe.start(); // Ensures that PrettyError is used app-wide.
app.use((err, req, res, next) => {
process.stderr.write(pe.render(err));
next();
});
export default app;
module.exports = {
// Server values
port: process.env.PORT || 3000,
host: process.env.VCAP_APP_HOST || 'localhost',
// App values
// Watson values
watson: {
opt_out_logging: process.env.WATSON_OPT_OUT_LOGGING || false,
conversation: {
username: process.env.WATSON_CONVERSATION_USERNAME,
password: process.env.WATSON_CONVERSATION_PASSWORD,
workspace: process.env.WATSON_CONVERSATION_WORKSPACE,
version_date: '2017-05-26',
},
discovery: {
username: process.env.WATSON_DISCOVERY_USERNAME,
password: process.env.WATSON_DISCOVERY_PASSWORD,
url: 'https://gateway.watsonplatform.net/discovery/api',
collection: 'news',
environment: 'system',
version_date: '2017-11-07',
},
speech_to_text: {
username: process.env.WATSON_STT_USERNAME,
password: process.env.WATSON_STT_PASSWORD,
url: 'https://stream.watsonplatform.net/speech-to-text/api',
},
},
};
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