How to connect data in Heroku to chartjs - node.js

How can punt the value of heorku query price_housing in to xValues in my chart?
In my html I have this chartjs that I want show in website
<canvas id="myChart" ></canvas>
<script>
var xValues = [50,60,70,80,90,100,110,120,130,140,150];
var yValues = [7,8,8,9,9,9,10,11,14,14,15];
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
legend: {display: true},
scales: {
yAxes: [{ticks: {min: 6, max:16}}],
}
}
});
</script>
And I have this connection with javascript that connect to Heroku and make query to extract price housing.
const {Client} = require('pg');
// Heroku connection
const connectionString =''
// Config connection
const connectionData = {
connectionString : connectionString,
ssl:{rejectUnauthorized: false}
};
const client = new Client(connectionData);
client.connect();
// Querys
const price_housing = client.query('SELECT price_housing FROM year_prince_housing ')
.then(response => {
console.log(response.rows)
client.end()
})
.catch(err => {
client.end()
});

Related

How we can call channel data parameter to Azure bot

const styleSet = window.WebChat.createStyleSet({
bubbleBackground: '#99ccff',
bubbleFromUserBackground: '#33adff',
rootHeight: '100%',
rootWidth: '100%'
});
styleSet.textContent = {
...styleSet.textContent,
fontFamily: "'Arial','Helvetica',sans-serif",
fontWeight: 'bold'
};
var channelObj = turnContext.Activity.ChannelData.ToString();
var channelData = Newtonsoft.Json.Linq.JObject.Parse(channelObj);
var customdata = channelData["TenantId"].ToString();
var d1 = window.WebChat.createDirectLine({ token })
window.WebChat.renderWebChat({
directLine: Object.assign({}, d1, {
postActivity: activity => {
var newActivity = object.assign({}, activity, { channelData: {
"TenantId": "#ViewBag.Tennatid"
}
});
alert("TenantId");
return d1.postActivity(newActivity);
}
}),
userID: 'YOUR_USER_ID',
username: 'Web Chat User',
locale: 'en-US',
// Passing 'styleSet' when rendering Web Chat
styleSet,
},
document.getElementById('webchat'));

React/Postgres sql detail: 'Failing row contains (43, ccc, null, 0, 2022-07-01 15:37:11.631)

**I am getting the error when I am connecting the frontend code as well as backend code with the database maybe the problem might be in front end but pls let me know the meaning of the error because I am newbie.I am getting the error on register pls help me and also when I register the website using frontend it shows me error on **localhost/register
enter image description here
const express = require('express');
const { listen } = require('express/lib/application');
const bodyParser=require('body-parser');
const bcrypt=require('bcrypt-nodejs')
const cors = require('cors')
const knex = require('knex');
const { response } = require('express');
const db=knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '224898',
database : 'smart-brain'
}
});
const app = express();
app.use(bodyParser.json());
app.use(cors())
const database={
users:[
{
id:'123',
name:'John',
email:'John#gmail.com',
password:'ABC',
entries:0,
joined:new Date()
},
{
id:'124',
name:'ABC',
email:'ABC',
password:'123',
entries:0,
joined:new Date()
}
],
login:[
{
id:'987',
hash:'',
email:'John#gmail.com'
}
]
}
app.get('/' ,(req,res)=>{
res.send(database.users);
})
app.post('/signin',(req,res)=>{
if(req.body.email===database.users[0].email && req.body.password===database.users[0].password){
res.json(database.users[0]);
}else{
res.status(400).json('error login in');
}
})
app.post('/register',(req,res)=>{
const{email,name,password}=req.body;
db('users')
.returning('*')
.insert({
email:email,
name:name,
joined: new Date()
})
.then(user=>{
res.json(user[0]);
})
. catch(err => console.log(err))
})
app.get('/profile/:id',(req,res)=>{
const{id}=req.params;
let found=false;
database.users.forEach(user=>{
if(user.id===id){
found=true;
return res.json(user);
}
})
if(!found){
res.status(400).json('not found');
}
})
app.put('/image',(req,res)=>{
const{id}=req.body;
let found=false;
database.users.forEach(user=>{
if(user.id===id){
found=true;
user.entries++
return res.json(user.entries);
}
})
if(!found){
res.status(400).json('not found');
}
})
// // Load hash from your password DB.
// bcrypt.compare("bacon", hash, function(err, res) {
// // res == true
// });
// bcrypt.compare("veggies", hash, function(err, res) {
// // res = false
// });
app.listen(3000,()=>{
console.log('app is running on port 3000 ');
})
AND ALSO I AM SHARING FRONTEND APP.JS CODE
APP.js code
import './App.css';
import Navigation from './Components/Navigation/Navigation';
import FaceRecognition from './Components/FaceRecognition/FaceRecognition';
import Logo from './Components/Logo/Logo'
import ImageLinkForm from './Components/ImageLinkForm/ImageLinkForm'
import Rank from './Components/Rank/Rank'
import { Component } from 'react';
import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";
import SignIn from './Components/SignIn/SignIn';
import Register from './Components/Register/Register'
const USER_ID = 'aad';
const PAT = 'bd69e06e68f244ed83b9ce09ee560e7c';
const APP_ID = 'aaa';
const MODEL_ID = 'face-detection';
const MODEL_VERSION_ID = '45fb9a671625463fa646c3523a3087d5';
const particlesOption = {
fpsLimit: 120,
particles: {
links: {
color: "#ffffff",
distance: 150,
enable: true,
opacity: 0.5,
width: 1,
},
collisions: {
enable: true,
},
move: {
direction: "none",
enable: true,
outModes: {
default: "bounce",
},
random: true,
speed: 5,
straight: true,
},
},
detectRetina: true,
}
const particlesInit = async (main) => {
await loadFull(main);
};
const initialState = {
input: '',
imageUrl: '',
box: {},
route:'signin',
isSignedIn:false,
user: {
id: '',
name: '',
email: '',
joined: '',
entries: 0
}
};
class App extends Component {
constructor() {
super();
this.state = initialState;
};
loadUser = (data) => {
this.setState({
user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined
}
})
}
apiData = () => {
const raw = JSON.stringify({
"user_app_id": {
"user_id": USER_ID,
"app_id": APP_ID
},
"inputs": [
{
"data": {
"image": {
"url": this.state.input
}
}
}
]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
return requestOptions;
}
displayFaceBox = (box) => {
this.setState({ box: box });
}
onInputChange=(event) =>{
this.setState({input: event.target.value});
}
onImageSubmit = () => {
this.setState({ imageUrl: this.state.input });
const requestOptions = this.apiData();
fetch("https://api.clarifai.com/v2/models/" + MODEL_ID + "/versions/" + MODEL_VERSION_ID + "/outputs", requestOptions)
.then(response => response.text())
.then(result => JSON.parse(result))
.then(obj => {
if (obj) {
fetch('http://localhost:3000/image', {
method: 'put',
headers: {'content-type': 'application/json'},
body: JSON.stringify({
id: this.state.user.id
})
})
.then(response => response.json())
.then(count => {
this.setState(Object.assign(this.state.user, {entries: count}))
})
}
this.displayFaceBox(this.calculateFaceLocation(obj))
})
.catch(error => console.log('error', error));
}
calculateFaceLocation = (data) => {
const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
const image = document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
return ({
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol: width - (clarifaiFace.right_col * width),
bottomRow: height - (clarifaiFace.bottom_row * height),
})
}
onRouteChange=(route)=>{
if(route==='signout'){
this.setState({isSignedIn:false})
}else if(route==='home'){
this.setState({isSignedIn:true})
}
this.setState({route:route})
}
render(){
const { imageUrl, box ,isSignedIn,route} = this.state;
return (
<div className="App">
<Particles className='particles'
init={particlesInit}
options={particlesOption}
/>
<Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange} />{ route==='home'?
<div>
<Logo />
<Rank name={this.state.user.name} entries={this.state.user.entries}/>
<ImageLinkForm onInputChange={this.onInputChange}
onImageSubmit={this.onImageSubmit}/>
<FaceRecognition box={box} imageUrl={imageUrl} />
</div> :(
route==='signin'?
<SignIn loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
: <Register loadUser={this.loadUser}onRouteChange={this.onRouteChange}/>
)
}
</div>
);
}
}
export default App;
Do not use images for textual information, copy and paste the text into the question. This would make the following easier.
From error message code:23502. If you go here Error codes you find that corresponds to 23502 not_null_violation. So the value that is being set to NULL is being entered into a column that has NOT NULL set. Your choices are:
a) Make sure the value is not set to NULL.
b) If you can have NULL values in the column drop the NOT NULL constraint.

How to update existing MongoDB document with Nested JSON using Angular?

I am trying to store JSON array to the existing document with the id who logged in. I don't have an idea how to post this array to backend.
cake.component.ts
export class CakeComponent implements OnInit {
form: FormGroup;
constructor(
public fb: FormBuilder,
private api: ApiService
) { }
ngOnInit() {
this.submitForm();
}
submitForm() {
this.form = this.fb.group({
url: ['', [Validators.required]],
width : ['', [Validators.required]],
height: ['', [Validators.required]]
})
}
submitForm() {
if (this.form.valid) {
this.api.AddCake(this.form.value).subscribe();
}
}
}
Existing MongoDB document Cakes
{
"id": "0001",
"type": "donut",
"name": "Cake"
}
Expected Output
{
"id": "0001",
"type": "donut",
"name": "Cake",
"image": {
"url": "images/0001.jpg",
"width": 200,
"height": 200
}
}
Here is the basic code, please update it accordingly :
/** You can split this code into multiple files, schema into a file &
mongoDB connectivity into a common file & actual DB update can be placed where ever you want */
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const cakeSchema = new Schema({
id: String,
type: String,
name: String,
image: {
url: String,
width: Number,
height: Number
}
});
const cakeModel = mongoose.model('Cakes', cakeSchema, 'Cakes');
let form = {
"url": "images/0001.jpg",
"width": 200,
"height": 200
}
async function myDbConnection() {
const url = 'yourDBConnectionString';
try {
await mongoose.connect(url, { useNewUrlParser: true });
console.log('Connected Successfully')
let db = mongoose.connection;
// You can use .update() or .updateOne() or .findOneAndUpdate()
let resp = await cakeModel.findOneAndUpdate({ id: '0001' }, { image: form }, { new: true });
console.log('successfully updated ::', resp)
db.close();
} catch (error) {
console.log('Error in DB Op ::', error);
db.close();
}
}
module.exports = myDbConnection();
Update :
In case if you're using mongoDB driver but not mongoose :
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'yourDBConnectionString';
// Database Name
const dbName = 'test';
// Create a new MongoClient
const client = new MongoClient(url);
let form = {
"url": "images/0001.jpg",
"width": 200,
"height": 200
}
// Use connect method to connect to the Server
client.connect(async function (err) {
if (err) console.log('DB connection error ::', err)
console.log("Connected successfully to server");
try {
// You can use .update() or .updateOne() or .findOneAndUpdate()
let resp = await client.db(dbName).collection('Cakes').findOneAndUpdate({ id: '0001' }, { $set: { image: form } }, { returnOriginal: false });
console.log('successfully updated ::', resp , 'resp value ::', resp.value)
client.close();
} catch (error) {
console.log('Error in DB Op ::', error);
client.close();
}
});

Export excel file using exceljs to client

I'm trying to export excel file using exceljs library. I'm using AngularJS and NodeJS.
Here is my code:
HTML:
<a class="btn m-b-xs btn-info btn-doc" ng-click="exportExcel()" style='background-color: #34495e; margin-left: 5%;'>
</a>
Controller:
$scope.exportExcel = function() {
$http.post('/api/exportExcel/exportExcel', {"data": $scope.data});
};
NodeJS:
const Excel = require('exceljs');
export async function exportExcel(req, res) {
try {
var workbook = new Excel.Workbook();
var worksheet = workbook.addWorksheet('My Sheet');
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Name', key: 'name', width: 32 },
{ header: 'D.O.B.', key: 'DOB', width: 10 }
];
worksheet.addRow({id: 1, name: 'John Doe', dob: new Date(1970,1,1)});
worksheet.addRow({id: 2, name: 'Jane Doe', dob: new Date(1965,1,7)});
var tempFilePath = tempfile('.xlsx');
workbook.xlsx.writeFile(tempFilePath).then(function() {
console.log('file is written');
res.sendFile(tempFilePath, function(err){
console.log('---------- error downloading file: ' + err);
});
});
} catch(err) {
console.log('OOOOOOO this is the error: ' + err);
}
}
I've just found this example of code for generating excel just to try get excel file on client side and after that i will create my own file.
But for now i just get in log this error
file is written
(node:25624) UnhandledPromiseRejectionWarning: TypeError: res.sendFile is not a function
Does anyone can help me to get excel file in browser after i click on button for export?
UPDATE
controller:
$scope.exportExcel = function() {
$http.post('/api/exportExcel/exportExcel', {"offer": $scope.offer})
.then(function(response) {
console.log(response.data);
var data = response.data,
blob = new Blob([data], { type: response.headers('content-type') }),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
});
};
html:
<a class="btn m-b-xs btn-info btn-doc" ng-click="exportExcel()" ng-href="{{ fileUrl }}" download="table.xlsx">
<i class="fa"></i>Export</a>
There were some problems, I have corrected them check and verify.
Definition of Route:-
var express = require("express");
var router = express.Router();
var fs = require("fs");
const Excel = require("exceljs");
var path = require("path");
router.get("/", async function(req, res, next) {
console.log("---InSideFunction---");
try {
var workbook = new Excel.Workbook();
var worksheet = workbook.addWorksheet();
worksheet.columns = [
{ header: "Id", key: "id", width: 10 },
{ header: "Name", key: "name", width: 32 },
{ header: "D.O.B.", key: "DOB", width: 10 }
];
worksheet.addRow({ id: 1, name: "John Doe", DOB: new Date(1970, 1, 1) });
worksheet.addRow({ id: 2, name: "Jane Doe", DOB: new Date(1965, 1, 7) });
workbook.xlsx
.writeFile("newSaveeee.xlsx")
.then(response => {
console.log("file is written");
console.log(path.join(__dirname, "../newSaveeee.xlsx"));
res.sendFile(path.join(__dirname, "../newSaveeee.xlsx"));
})
.catch(err => {
console.log(err);
});
} catch (err) {
console.log("OOOOOOO this is the error: " + err);
}
});
module.exports = router;
req and res are not associated with 'exceljs'.

Does the schema have to match completely to return anything? (mongoose)

I have a very simple backend server and client looking to display data from a mongo db, there are documents in a collection called cards in a database called test.
When I run the regex from this file it gives me back one document, but when I search it through the api on the backend it gives me nothing, no error, just "true" and "data: " in the console.
cconst mongoose = require("mongoose");
const express = require("express");
var cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const Data = require("./data");
const Card = require("./card");
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
// this is our MongoDB database
const dbRoute =
"mongodb+srv://dbUser:PASSWORD#cluster0-jhfnc.mongodb.net/test?retryWrites=true";
// connects our back end code with the database
mongoose.connect(dbRoute, { useNewUrlParser: true });
let db = mongoose.connection;
db.once("open", () => console.log("connected to the database"));
// checks if connection with the database is successful
db.on("error", console.error.bind(console, "MongoDB connection error:"));
// (optional) only made for logging and
// bodyParser, parses the request body to be a readable json format
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger("dev"));
// this is our get method
// this method fetches all available data in our database
router.get("/getCardsByName/:cardName", (req, res) => {
const { name } = req.params.cardName;
Card.find({ name: { $regex: ".*" + name + ".*" } }, (err, cards) => {
if (err) return res.json({ success: false, error: err });
console.log("data: " + cards);
return res.json({ success: true, cards: cards });
});
});
// append /api for our http requests
app.use("/api", router);
// launch our backend into a port
app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));
The client looks like this:
// /client/App.js
import React, { Component } from "react";
import axios from "axios";
class App extends Component {
// initialize our state
state = {
cards: [],
id: 0,
message: null,
intervalIsSet: false,
idToDelete: null,
idToUpdate: null,
objectToUpdate: null,
cardToSearch: null
};
// when component mounts, first thing it does is fetch all existing data in our db
// then we incorporate a polling logic so that we can easily see if our db has
// changed and implement those changes into our UI
componentDidMount() {
//this.getDataFromDb();
if (!this.state.intervalIsSet) {
let interval = setInterval(this.getDataFromDb, 1000);
this.setState({ intervalIsSet: interval });
}
}
// never let a process live forever
// always kill a process everytime we are done using it
componentWillUnmount() {
if (this.state.intervalIsSet) {
clearInterval(this.state.intervalIsSet);
this.setState({ intervalIsSet: null });
}
}
getCardByCardName = card_name => {
fetch(`http://localhost:3001/api/getCardsByName/${card_name}`)
.then(cards => cards.json())
.then(res => this.setState({ cards: res.cards }));
};
render() {
const { cards } = this.state;
return (
<div>
<ul>
{cards.length <= 0
? "No Cards Found"
: cards.map(card => (
<li style={{ padding: "10px" }} key={card.id}>
<span style={{ color: "gray" }}> id: </span> {card.id} <br />
<span style={{ color: "gray" }}> data: </span>
{card.name}
</li>
))}
</ul>
<div style={{ padding: "10px" }}>
<input
type="text"
style={{ width: "200px" }}
onChange={e => this.setState({ cardToSearch: e.target.value })}
placeholder="Card name"
/>
<button
onClick={() => this.getCardByCardName(this.state.cardToSearch)}
>
FIND
</button>
</div>
</div>
);
}
}
export default App;
And the schema looks like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// this will be our data base's data structure
const CardSchema = new Schema(
{
_id: Schema.Types.ObjectId,
armor: Number,
artist: String,
attack: Number,
cardClass: String,
classes: Array,
collectible: Boolean,
collectionText: String,
cost: Number,
dbfld: Number,
durability: Number,
elite: Boolean,
entourage: Array,
faction: String,
flavor: String,
health: Double,
hideStats: Boolean,
howToEarn: String,
howToEarnGolden: String,
id: String,
mechanics: Array,
multiClassGroup: String,
name: String,
overload: Number,
playRequirements: Object,
questReward: String,
race: String,
rarity: String,
referencedTags: Array,
set: String,
spellDamage: Double,
targettingArrowText: String,
text: String,
type: String
},
{ timestamps: true }
);
// export the new Schema so we could modify it using Node.js
module.exports = mongoose.model("Card", CardSchema);
It turns out I was using destructuring incorrectly. It should be:
router.get("/getCardsByName/:cardName", (req, res) => {
**const name = req.params.cardName;**
console.log(name);
Card.find({ name: { $regex: ".*" + name + ".*" } }, (err, cards) => {
if (err) return res.json({ success: false, error: err });
console.log("data: " + cards);
return res.json({ success: true, cards: cards });
});
});

Resources