How to convert a template from jade to HBS? - javascript

I am not too familiar with the jade template language, but quite familiar with handle bars. I need to use hbs because my project is based on hbs.
I have the following the braintree payment for nodejs express, and their view was based on jade.
https://github.com/braintree/braintree_express_example/blob/master/views/checkouts/new.jade
form#payment-form(action="/checkouts", method="post")
section
.bt-drop-in-wrapper
#bt-dropin
label(for="amount")
span.input-label Amount
.input-wrapper.amount-wrapper
input#amount(name="amount" type="tel" min="1" placeholder="Amount" value="10")
button.button(type="submit")
span Test Transaction
script(src="https://js.braintreegateway.com/js/braintree-2.27.0.min.js")
script.
(function () {
var checkout = new Demo({
formID: 'payment-form'
});
var token = "#{clientToken}";
braintree.setup(token, "dropin", {
container: "bt-dropin"
});
Below is my router
router.post('/', parseUrlEnconded, function (request, response) {
var transaction = request.body;
gateway.transaction.sale({
amount: 7,
paymentMethodNonce: transaction.payment_method_nonce
}, function (err, result) {
if (err) throw err;
if (result.success) {
[...]
I essentially want the payment form to be shown in view, and the payment_method_nonce value submitted to the server

Use jade-to-handlebars, which is a nodejs module to do exactly what you ask.

Related

How to pass custom parameters to sendy via node js api?

I am trying to pass custom data in sendy via api of sendy. Sendy has custom field attributes in which we can pass data. I am using a sendy node js package whose link is provided on sendy website. the issue is that i am not able to pass custom field data to sendy api. Here is my code
var params = {
email: email2,
custom: {
'assignmentDetail':assignmentLink,
'submissionDetail':submissionDetail,
'FormLink':reviewerFormLink,
},
list_id: ListID,
api_key: 'vQzxtX76pNFekG4w5BzC'
};
sendy.subscribe(params, function (err, result) { if (err){
console.log(err.toString());
}else{
UpdateData(recordID, email2, ListID);
console.log('Subscribed succesfully');}
});
the custom field data is not being passed in the sendy. Please help
I have found the solution to my problem. It is very simple. You need to make your custom fields in enclosed in quotes and you are done. Just like this
var params = {
email: email2,
//make sure custom field names are same otherwise sendy would igore the fields
'assignmentDetail':assignmentLink,
'submissionDetail':submissionDetail,
'FormLink':reviewerFormLink,
list_id: ListID,
api_key: 'vQzxtX76pNFekG4w5BzC'
};
sendy.subscribe(params, function (err, result) { if (err){
console.log(err.toString());
}else{
UpdateData(recordID, email2, ListID);
console.log('Subscribed succesfully');}
});

Need some help regarding the Elasticsearch engine and react js

I hope you are doing well, I need some help regarding the Elasticsearch engine. what I am doing is I am trying to create a search engine I have successfully post my data through kibana to elasticsearch engine. but "but how can I add the search component of elastyicsearch to my react app", I have like 4 million records into the kibana index, when I try to search directly from react it take a long time to display records into my frontapp app with nodejs api. below is the code with nodejs but the problem with this code it just gives me 10 records only.
router.get('/tweets', (req, res)=>{
let query = {
index: 'tweets',
// size: 10000
}
if(req.query.tweets) query.q = `*${req.query.tweets}*`;
client.search(query)
.then(resp => {
return res.status(200).json({
tweets: resp.body.hits.hits
});
})
.catch(err=>{
console.log(err);
return res.status(500).json({
err
});
});
});
Is there any way to impliment elasticsearch component directly to my reactjs app. like with the localhost:9200/index.. directly from the elasticsearch api?
Your request to Elasticsearch looks a bit strange to me, have you tried to search using a body like in the documentation? This line:
if(req.query.tweets) query.q = `*${req.query.tweets}*`;
doesn't seem like a correct way to write a query. Which field do you want to search for?
I saw that you tried to use the size field, which should be correct. You can also try the following:
client.search({
index: 'tweets',
body: {
size: 1000, // You can put the size here to get more than 10 results
query: {
wildcard: { yourfield: `*${req.query.tweets}*` }
}
}
}, (err, result) => {
if (err) console.log(err)
})
You could use SearchKit to directly query elasticsearch from you react app. But be aware that exposing DB services outside of your own infrastructure is bad practice.
You can use the component like this:
import {
SearchkitManager,
SearchkitProvider,
SearchkitComponent
} from 'searchkit'
const searchkit = new SearchkitManager(host)
class Render extends SearchkitComponent {
render(){
let results = await this.searchkit.reloadSearch()
return <div>{results}</div>
}
}
function table(){
return <SearchkitProvider searchkit={searchkit}>
<Render />
</SearchkitProvider>
}

How to access Angular Js data from nodejs

Hi in my angular js file, I have patient objects which contain name, number and appointment date. In my node js file, I use twilio to send a text a patient. What I want to know is how to get the number from the angular js file in order to use it in my node Js file so I can send the patient a text. Thanks.
here is the part of server.js where I send the text message
app.post('/testtwilio', function(req,res){
var cheerio = require('cheerio'),
$ = cheerio.load('file.html'),
fs = require('fs');
fs.readFile('./views/index.html', function (err, html) {
if (err) {
throw err;
} else {
$ = cheerio.load(html.toString());
console.log($scope.patients)//$('.reminder').attr('text'));
}
});
client.sendMessage({
to: '{{patient.number}}',
from: '+16173935460',
body: 'Text sent using NodeJS'
}, function(err, data){
if(err)
console.log(err);
});
})
Here is the patient object in the MainController.js
$scope.patients = [
{
name: 'John Smith',
date: "12/22/2016",
number: 1829191844
},
{
name: 'Matt',
date: "09/15/2016",
number: 1829198344
},
{
name: 'John',
date: "08/25/2016",
number: 1829198844
},
];
Pass the data from the front end to the backend? Have angular call a route on your backend with the data you need and access it with the req.params object.
Is your server.js a node.js controller?
In the angular controller you could import $http and just do a $http.post({myparams}, /myRoute, function(results){console.log(results)})
Like Mike says. The only way to really share files between the front end and the backend is if the files are JSON as that can be read by Angular and Node. However, I usually just use this for static configuration files.

Server side validation in Express compatible with a single page Angular application

I would like to perform server side validation, preferably with expressValidator. When saving a resource, I check to see if it is valid. If it's not valid what should I return?
There are examples:
http://blog.ijasoneverett.com/2013/04/form-validation-in-node-js-with-express-validator/
https://github.com/ctavan/express-validator
Unfortunately, I can't figure out my answer from that.
In Angular, I am using the $resource service. When I do a save, and there is a validation error, how should the server send this back? Note, this is a single page application.
Also, how should I handle this on the client side? Is this technically a success call?
Please, I am not looking for any instant, ajax, check per field solution. I want to submit save, if there is a problem, I would like to return the errors so that Angular can handle them. This does not need to be the perfect solution, just something to set me on the right track.
I am not handing the Angular code in an special way at the moment:
Controller:
$scope.saveTransaction = function (transaction) {
transactionData.saveTransaction(transaction);
}
Service
saveTransaction: function(transaction) {
return resource.save(transaction);
}
The server side code looks as follows:
app.post('/api/transactions', function (req, res) {
var transaction;
req.assert('amount', 'Enter an amount (numbers only with 2 decimal places, e.g. 25.50)').regex(/^\d+(\.\d{2})?$/);
var errors = req.validationErrors();
var mapped = req.validationErrors(true);
if (mapped) {console.log("MAPPED")};
//console.log(mapped);
if(!errors) {
console.log("Passed");
transaction = new TransactionModel({
date: req.body.date,
description: req.body.description,
amount: req.body.amount
});
transaction.save(function (err) {
if (!err) {
return console.log("created");
} else {
return console.log("err");
}
return res.send(transaction);
})
}
else {
console.log("Errors");
res.send(errors);
// res.render('Transaction', {
// title: 'Invalid Transaction',
// message: '',
// errors: errors
// });
}
});
You could send and handle "better" errors:
SERVER
res.json(500, errors)
CLIENT
resource.save(tran).then(function(){
//it worked
},
function(response) {
//it did not work...
//see response.data
});

AngularJS redirection after ng-click

I have a REST API that read/save data from a MongoDB database.
The application I use retrieves a form and create an object (a job) from it, then save it to the DB. After the form, I have a button which click event triggers the saving function of my controller, then redirects to another url.
Once I click on the button, I am said that the job has well been added to the DB but the application is jammed and the redirection is never called. However, if I reload my application, I can see that the new "job" has well been added to the DB. What's wrong with this ??? Thanks !
Here is my code:
Sample html(jade) code:
button.btn.btn-large.btn-primary(type='submit', ng:click="save()") Create
Controller of the angular module:
function myJobOfferListCtrl($scope, $location, myJobs) {
$scope.save = function() {
var newJob = new myJobs($scope.job);
newJob.$save(function(err) {
if(err)
console.log('Impossible to create new job');
else {
console.log('Ready to redirect');
$location.path('/offers');
}
});
};
}
Configuration of the angular module:
var myApp = angular.module('appProfile', ['ngResource']);
myApp.factory('myJobs',['$resource', function($resource) {
return $resource('/api/allMyPostedJobs',
{},
{
save: {
method: 'POST'
}
});
}]);
The routing in my nodejs application :
app.post('/job', pass.ensureAuthenticated, jobOffers_routes.create);
And finally the controller of my REST API:
exports.create = function(req, res) {
var user = req.user;
var job = new Job({ user: user,
title: req.body.title,
description: req.body.description,
salary: req.body.salary,
dueDate: new Date(req.body.dueDate),
category: req.body.category});
job.save(function(err) {
if(err) {
console.log(err);
res.redirect('/home');
}
else {
console.log('New job for user: ' + user.username + " has been posted."); //<--- Message displayed in the log
//res.redirect('/offers'); //<---- triggered but never render
res.send(JSON.stringify(job));
}
});
};
I finally found the solution ! The issue was somewhere 18inches behind the screen....
I modified the angular application controller like this :
$scope.save = function() {
var newJob = new myJobs($scope.job);
newJob.$save(function(job) {
if(!job) {
$log.log('Impossible to create new job');
}
else {
$window.location.href = '/offers';
}
});
};
The trick is that my REST api returned the created job as a json object, and I was dealing with it like it were an error ! So, each time I created a job object, I was returned a json object, and as it was non null, the log message was triggered and I was never redirected.
Furthermore, I now use the $window.location.href property to fully reload the page.

Categories

Resources