Archive for the ‘REACTJS’ Category

simple git, yarn, react, mongo project checklist

Wednesday, December 13th, 2017

mkdir foo && cd $_

git init

yarn add react

vi yarn.lock (if you’d like to see versions)

git add package.json yarn.lock

echo “/node_modules” >> .gitignore

git add .gitignore

touch README

git add README

git remote add origin git@github.som:credentials/foobar.git

git commit -m “Initial commit”

git push -u origin master

git checkout -b develop

git push -u origin develop

git checkout -b feature/foo develop

vi foo.js

git add foo.js

git commit -m “New foo file”

git rebase develop (if we believe changes have been made to origin develop, will pull those and then apply our commits)

git checkout develop

git merge feature/foo

git push

git checkout -b release/1.0 develop

git push -u origin release/1.0

git checkout -b hotfix/1.0 develop

etc.

——————

example index connecting to mongo:

require(‘dotenv’).config();

var MongoClient = require(‘mongodb’).MongoClient;

MongoClient.connect(process.env.MONGO_URI, function(err, db) {

    if (err) {

        console.log(‘Cannot connect to MongoDB!’, err);

    } else {

        console.log(‘Connected to MongoDB!’);

    }

});

(put env vars in .env file)

vi .env

MONGO_URI = mongodb://localhost:27017/foo

yarn add mongodb

yarn add dotenv

(have mongo installed and started first!):

brew install mongodb —with-openssl

brew services start mongodb

Connected to MongoDB!”

ReactJS Next.js Isomorphic replace cp CodeIgniter Frontend

Friday, December 1st, 2017

Setup

  • Install nvm
  • Target node 6.6.0
    • nvm install 6.6.0
    • nvm use 6.6.0
  • yarn install
  • yarn run dev to start application in development environment

Testing

get-help-fe uses Jest + Enzyme for component testing.

  • yarn run test will run all tests
  • yarn run test:watch will watch/run tests when changes are made
  • yarn run coverage will produce code coverage reports
    • An HTML file located at coverage/icov-report/index.html contains a clean code coverage report

Directory Structure

  • _tests_/ – Jest/Enzyme unit tests
  • actions/ – Redux Actions
  • components/ – Reusable React components
  • config/ – Keystone pipeline configuration
  • coverage/ – Code coverage report output directory
  • dist/ – Bundled code used for code-splitting and production builds
  • layouts/ – Higher-order React components that wrap pages, aka: layouts, themes, templates
  • pages/ – Single instance React components implemented as pages
  • pipelines/ – node-pipeline specific build pipeline configuration
  • reducers/ – Redux reducers
  • static/ – Directory used to host static assets for serving without pre-processing (images, fonts, etc)
  • .babelrc – Configuration file for Babel – transpiles ES6 to better supported ECMA2015 for end users
  • .eslintrc – Configuration file for ESLint
  • api.js – API endpoint definitions
  • application.yaml – Keystone build pipeline configuration
  • next.config.js – Next.js configuration file
  • package.json – Application dependencies
  • pm2.json – PM2 Application Monitoring
  • redirects.js – Legacy URL path redirects
  • routes.js – Application routes
  • server.js – Application server
  • yarn.lock – Yarn lock file — Do not edit, always commit!

Electron ReactJS PHP Oracle Service Cloud Multiple Interfaces Quick Deploy via Curl

Friday, December 1st, 2017

quick-deploy

Electron application boilerplate based on ReactReduxReact RouterWebpackReact Transform HMR for rapid application development

Install

  • Note: requires a node version >= 6 and an npm version >= 3.

First, clone the repo via git

Install dependencies with yarn

yarn install

:bulb: In order to remove boilerplate sample code, simply run yarn run cleanup. After this is run, the initial sample boilerplate code will be removed in order for a clean project for starting custom dev

$ yarn run dev

CSS Modules

This boilerplate out of the box is configured to use css-modules.

All .css file extensions will use css-modules unless it has .global.css.

If you need global styles, stylesheets with .global.css will not go through the css-modules loader. e.g. app.global.css

If you want to import global css libraries (like bootstrap), you can just write the following code in .global.css:

@import "~bootstrap/dist/css/bootstrap.css";

Packaging

To package apps for the local platform:

$ yarn run package

To package apps for all platforms:

 

$ yarn run package-all

To package apps with options:

$ yarn run package -- --[option]

Further commands

To run the application without packaging run

$ yarn run build
$ yarn start

To run End-to-End Test

$ yarn run build
$ yarn run test-e2e

Options

See electron-builder CLI Usage

Module Structure

This boilerplate uses a two package.json structure.

  1. If the module is native to a platform or otherwise should be included with the published package (i.e. bcrypt, openbci), it should be listed under dependencies in ./app/package.json.
  2. If a module is imported by another module, include it in dependencies in ./package.json. See this ESLint rule.
  3. Otherwise, modules used for building, testing and debugging should be included in devDependencies in ./package.json.

 

NodeJS ReactJS, NOT using Isomorphic-fetch, using jQuery JSONP GET -> Oracle Service Cloud Article Feedback ci/ajaxCustom Endpoint

Friday, June 23rd, 2017

app.js

'use strict';

const compression = require('compression');
const express = require('express');
const next = require('next');
const path = require('path');
const fetch = require('isomorphic-fetch');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const auth = '...';
const site = 'help-*-*';
const server = express();

class GetHelp {
constructor() {

this.initApp();
}

/*
Start express application and express healthcheck.
*/
initApp() {
app.prepare().then(() => {

/*
* API Server
*/

server.get('/api/search/:searchTerm', (req, res, next) => {
const searchTerm = req.params.searchTerm;
var endpoint = `services/rest/connect/v1.3/analyticsReportResults`;

fetch(
`https://${auth}@${site}.....com/${endpoint}`, {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify({
"id": 178394,
"filters": [{
"name": "os_search",
"values": [
searchTerm
]
}]
})
})
.then(function(res) { return res.json(); })
.then(function(data) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ article: data }));
});
});

server.get('/api/article/:articleId', (req, res, next) => {
const articleId = req.params.articleId;
var endpoint = "";
if (parseInt(articleId)) {
endpoint = `/services/rest/connect/v1.3/answers/${articleId}/?fields=solution,summary`;
} else {
endpoint = `/services/rest/connect/v1.3/queryResults/?query=select summary,solution from answers where customFields.c.slug='${articleId}'and customFields.c.lang_id=2035 and language=1 and AccessLevels.NamedIDList.ID=11`;
}

fetch(
`https://${auth}@${site}.....com/${endpoint}`, {
method: 'GET',
mode: 'no-cors',
})
.then(function(res) { return res.json(); })
.then(function(data) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ article: data }));
});
});

var endpoint = "services/rest/connect/v1.3/queryResults/?query=select lookupName,value from messageBases ";
endpoint += "where lookupName in (" + msgToGet + ")";

fetch(
`https://${auth}@${site}.....com/${endpoint}`, {
method: 'GET',
mode: 'no-cors',
})
.then(function(res) { return res.json(); })
.then(function(data) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ messageBase: data }));
});
});

/*
* APP Routes
*/

server.get('/search/:searchTerm/page/:page', (req, res) => {
const params = { searchTerm: req.params.searchTerm, page: req.params.page }
return app.render(req, res, '/search', params);
});

server.get('/article/:articleId', (req, res) => {
const params = { articleId: req.params.articleId }
return app.render(req, res, '/article', params);
});

server.get('*', (req, res) => {
return handle(req, res);
});

server.listen(8080, 'local-www....dev.com', () => {
this.initHealthcheck();
});
});
}

}

module.exports = new GetHelp();

/components/StarRating.js

</pre></pre>
import React from 'react';

import Link from '../components/Link';

import Router from 'next/router'

import 'isomorphic-fetch';

import Modal from 'react-modal';

&nbsp;

&nbsp;

const site = 'help-en-us';

const customStyles = {

content : {

top: '50%',

left: '50%',

right: 'auto',

bottom: 'auto',

marginRight: '-50%',

transform: 'translate(-50%, -50%)'

}

};

&nbsp;

&nbsp;

export default class extends React.Component {

constructor(props) {

super(props);

this.state = {

starRating: 0,

articleId: this.props.articleId,

thankYou: false,

showStars: true

};

&nbsp;

&nbsp;

this.handleStar = this.handleStar.bind(this);

this.submitRating = this.submitRating.bind(this);

this.getToken = this.getToken.bind(this);

this.onKeyPress = this.onKeyPress.bind(this);

this.openModal = this.openModal.bind(this);

this.afterOpenModal = this.afterOpenModal.bind(this);

this.closeModal = this.closeModal.bind(this);

this.cancelModal = this.cancelModal.bind(this);

this.submitAnswerFeedback = this.submitAnswerFeedback.bind(this);

this.getToken = this.getToken.bind(this);

}

&nbsp;

&nbsp;

async submitRating(rating) {

let result = await $.ajax({

url: `http://${site}.....com/ci/ajaxCustom/submitAnswerRating`,

data: `a_id=${this.props.articleId}&amp;amp;rate=${rating}&amp;amp;options_count=5`,

dataType: 'jsonp',

jsonpCallback: 'submitAnswerRating',

success: function(response){

console.log(response.submitted);

}

});

let flag = await result;

return flag

};

&nbsp;

&nbsp;

async getToken(rating){

let result = await $.ajax({

url: `http://${site}.....com/ci/ajaxCustom/getNewFormToken`,

data: `formToken=${Math.random().toString(36).substr(2)}`,

dataType: 'jsonp',

jsonpCallback: 'getNewFormToken',

success: function(response){

//console.log(typeof(response.newToken));

return response;

}

});

let token = await result;

return token

};

&nbsp;

&nbsp;

async submitAnswerFeedback(){

let a_id = this.props.articleId;

let rating = this.state.starRating;

let feedbackMessageValue = this.state.feedbackMessageValue;

let token = this.state.token;

console.log('sAF: ' + token);

&nbsp;

&nbsp;

let result = await $.ajax({

url: `http://${site}.....com/ci/ajaxCustom/submitAnswerFeedback`,

data: `a_id=${a_id}&amp;amp;rate=${rating}&amp;amp;message=${feedbackMessageValue}&amp;amp;f_tok=${token}`,

dataType: 'jsonp',

jsonpCallback: 'submitAnswerFeedback',

success: function(response){

console.log(response);

}

});

&nbsp;

&nbsp;

let message = await result;

this.closeModal();

&nbsp;

&nbsp;

return message

};

&nbsp;

&nbsp;

async handleStar(rating){

// submit the star rating clicked

let ratingSubmitted = await this.submitRating(rating);

if(rating >= 3){

// submitted, and done

this.setState({

thankYou: true,

starRating: rating,

ratingSubmitted: ratingSubmitted,

showStars: false

})

} else {

// less than 3, so get a token, and open popup

let token = await this.getToken(rating);

console.log('obj: ' + token.newToken);

console.log(typeof(token.newToken));

this.openModal();

this.setState({

thankYou: true,

starRating: rating,

ratingSubmitted: ratingSubmitted,

token: token.newToken,

showStars: false

})

}

}

&nbsp;

&nbsp;

onKeyPress(e) {

let feedbackMessageValue = e.target.value;

}

&nbsp;

&nbsp;

onChange(e) {

let feedbackMessageValue = e.target.value;

this.setState({

feedbackMessageValue: feedbackMessageValue

});

}

&nbsp;

&nbsp;

openModal() {

this.setState({

modalIsOpen: true

});

}

&nbsp;

&nbsp;

afterOpenModal() {

// references are now sync'd and can be accessed.

this.subtitle.style.color = '#f00';

}

&nbsp;

&nbsp;

closeModal() {

this.setState({

modalIsOpen: false

});

}

&nbsp;

&nbsp;

cancelModal() {

this.setState({

modalIsOpen: false,

showStars: true,

thankYou: false

})

}

&nbsp;

&nbsp;

render () {

const stars = [1,2,3,4,5];

const starRating = this.state.starRating;

const thankYou = this.state.thankYou;

const showStars = this.state.showStars;

&nbsp;

&nbsp;

return (

&nbsp;

&nbsp;

<div className="box">

<div className="answerFeedback">

{!thankYou ? <div className="title">Please rate this article:</div> : ""}

{showStars ? (  <div className="starsBox">

{

stars.map((star) => {

return(

<span

key={star}

className={`g72-star ${star<=starRating?'selectedStar':''}`}

onClick={(e) => this.handleStar(star)}>

</span>

)

})

}

</div>) : (<span></span>)

}

{thankYou ? <div className="thankYou">Thank you for your feedback!</div> : ""}

<div> {

//<button onClick={this.openModal}>Open Modal</button> }

<Modal

isOpen={this.state.modalIsOpen}

onAfterOpen={this.afterOpenModal}

onRequestClose={this.closeModal}

style={customStyles}

contentLabel="Example Modal">

&nbsp;

<h2 ref = { subtitle => this.subtitle = subtitle }>Provide Additional Information</h2>

<div className = "submittedMessage">Your rating has been submitted, please tell us how we can make this answer more useful.</div>

<div className = "faqQuestion">FAQ Feedback – How can we improve this answer? *</div>

<textarea

className = "feedbackMessage"

id = "feedbackMessage"

name = "feedbackMessage"

rows = "4"

cols = "50"

value = { this.state.feedbackMessageValue }

onKeyPress = { (e) => this.onKeyPress(e) }

onChange={(e) => this.onChange(e)}></textarea>

<div className="formButtons">

<button onClick = { this.submitAnswerFeedback } className="submitButton">Submit</button>

<button onClick = { this.cancelModal } className="cancelButton">Cancel</button>

</div>

&nbsp;

&nbsp;

</Modal>

</div>

</div>

<style jsx>{`

.answerFeedback .title {

font-weigth: bold;

}

.answerFeedback .g72-star {

font-size: 1.5em;

margin: 5px;

cursor: pointer;

color: #6d6b6b;

}

.answerFeedback .g72-star:hover, .selectedStar{

color: rgb(251, 224, 0) !important;

}

.starsBox {

background: #a09e9e;

border-radius: 10px;

padding: 0 10px;

width: 170px;

text-align: center;

}

.feedbackMessage {

border: 1px solid;

margin: 10px 10px 10px 0;

padding: 10px;

width: 100%;

}

.formButtons {

text-align: right;

}

.submitButton, .cancelButton {

width: 100%;

margin: 0;

padding: 10px;

font-weight: bold;

color: white;

text-transform: uppercase;

border-radius: 3px;

text-align: center;

text-decoration: none;

}

.submitButton {

background-color: rgba(250, 84, 0, 1);

}

.submitButton:hover {

background-color: #666;

}

.cancelButton {

background-color: rgb(153, 153, 153);

}

.cancelButton:hover {

background-color: #666;

}

.submitbutton:hover {

&nbsp;

&nbsp;

}

`}</style>

</div>

);

}

}
<pre>
Oracle AjaxCustom Service endpoint
function submitAnswerRating()
 {
 $answerID = $this-&amp;gt;input-&amp;gt;get('a_id');
 $rating = $this-&amp;gt;input-&amp;gt;get('rate');
 $scale = $this-&amp;gt;input-&amp;gt;get('options_count');
 if($answerID){
 if($this-&amp;gt;model('Answer')-&amp;gt;rate($answerID, $rating, $scale)){
 print "submitAnswerRating({'submitted':'true'})";
 }else{
 print "submitAnswerRating({'submitted':'false'})";
 }
 }
 }
 
 function getNewFormToken()
 {
 if($formToken = $this-&amp;gt;input-&amp;gt;get('formToken'))
 {
 $newToken = Framework::createTokenWithExpiration(0, false);
 print "getNewFormToken({'newToken':'" . $newToken . "'})";
 }
 }
 
 function submitAnswerFeedback()
 {
 AbuseDetection::check();
 $answerID = $this-&gt;input-&gt;get('a_id');
 if($answerID === 'null')
 $answerID = null;
 $rate = $this-&gt;input-&gt;get('rate');
 $message = $this-&gt;input-&gt;get('message');
 $givenEmail = '...@....com';
 $threshold = 3;
 $optionsCount = 5;
 $formToken = $this-&gt;input-&gt;get('f_tok');
 $incidentResult = $this-&gt;model('Incident')-&gt;submitFeedback($answerID, $rate, $threshold, null, $message, $givenEmail, $optionsCount);
 if($incidentResult-&gt;result){
 print "submitAnswerFeedback({'ID':'" . $incidentResult-&gt;result-&gt;ID . "'})";
 //$this-&gt;_renderJSON(array('ID' =&gt; $incidentResult-&gt;result-&gt;ID));
 }else{
 if($incidentResult-&gt;error){
 print "submitAnswerFeedback({'error 2':'" . $incidentResult-&gt;error-&gt;externalMessage . "'})";
 }
 }