Node.js - how to use external library (VersionOne JS SDK)? - javascript

I'm trying to use VersionOne JS SDK in Node.js (https://github.com/versionone/VersionOne.SDK.JavaScript). I'm simply downloading whole library, placing it alongside with my js file:
var v1 = require('./v1sdk/v1sdk.js');
var V1Server = v1.V1Server;
console.log(v1);
console.log(V1Server);
Unfortunately something seems wrong, the output I get after calling
node app.js
is:
{}
undefined
Can somebody point me what I'm doing wrong or check whether the sdk is valid.
Thanks!

You can see in the source where V1Server is defined, that it's a class with a constructor. So you need to use the new keyword and pass the arguments for your environment.
https://github.com/versionone/VersionOne.SDK.JavaScript/blob/master/client.coffee#L37
var server = new V1Server('cloud'); //and more if you need

Can you try the sample.js script that I just updated from here:
https://github.com/versionone/VersionOne.SDK.JavaScript/blob/master/sample.js
It pulls in the two modules like this:
var V1Meta = require('./v1meta').V1Meta;
var V1Server = require('./client').V1Server;
var hostname = "www14.v1host.com";
var instance = "v1sdktesting";
var username = "api";
var password = "api";
var port = "443";
var protocol = "https";
var server = new V1Server(hostname, instance, username, password, port, protocol);
var v1 = new V1Meta(server);
v1.query({
from: "Member",
where: {
IsSelf: 'true'
},
select: ['Email', 'Username', 'ID'],
success: function(result) {
console.log(result.Email);
console.log(result.Username);
console.log(result.ID);
},
error: function(err) { // NOTE: this is not working correctly yet, not called...
console.log(err);
}
});
You might have to get the latest and build the JS from CoffeeScript.
I think I was trying out "browserify" last year and that's how the "v1sdk.js" file got generated. But I'm not sure if that's the best approach if you're using node. It's probably better just to do it the way the sample.js file is doing it.
However, I did also check in a change to v1sdk.coffee which property exports the two other modules, just as a convenience. With that, you can look at sample2.js. The only different part there is this, which is more like you were trying to do with your example:
var v1sdk = require('./v1sdk');
var hostname = "www14.v1host.com";
var instance = "v1sdktesting";
var username = "api";
var password = "api";
var port = "443";
var protocol = "https";
var server = new v1sdk.V1Server(hostname, instance, username, password, port, protocol);
var v1 = new v1sdk.V1Meta(server);

Related

Springboot with Javascript and MYSQL

I'm creating a filter page in springboot that works fine. When I add my javascript to the html page to make a query using an .change event listener, I want to use this query to live show available results before submitting the form. It looks like this (shorter version, otherwise its just var declaration that's not part of the problem)
$("#leadsForm").change(function () {
//revenue
var revMin = document.getElementById("revenueMin").value
var revMax = document.getElementById("revenueMax").value
//reg date
var regDateMin = document.getElementById("regDateMin").value
var regDateMax = document.getElementById("regDateMax").value
var mainBranch = $('#mainBranch').val();
var specificBranch = $('#specificBranch').val();
var county = $('#county').val();
var tel = document.getElementById("containsTel").value
var contactPerson = document.getElementById("containsContactPerson").checked
var location = document.getElementById("containsLocation").checked
var employed = document.getElementById("containsEmployed").checked
var keyValues = document.getElementById("containsKeyValues").checked
var email = document.getElementById("containsEmail").checked
var website = document.getElementById("containsWebsite").checked
var wholeQuery = "SELECT "+selectedColumns + " from company" + " WHERE " + revenueSelector +
regDateSelector + branchSelector +
countySelector + telSelector + keyValuesSelector + contactPersonSelector + emailSelector +
websiteSelector + locationSelector + employedSelector;
console.log(wholeQuery)
I want to find a way to use this query, JAVASCRIPT SIDE to make the available result change on the .change eventlistener based on userinput, variables above in my variable "wholeQuery".
I use the code
const mysql = require((["mysql"]))
const db = mysql.createConnection({
host : "localhost",
user : "*****",
password: "*****",
database: "mydb"
})
console.log(db)
but get the Error:
Uncaught Error: Script error for "mysql"
https://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:5)
at HTMLScriptElement.onScriptError (require.js:5)
The problem is that I can't connect to my SQL database through Javascript, is there any other way than the one above? I'm doing the solution most other threads recommend but its not working in my case because my project is not a node.js project.
I am a little confused, why connect directly to MySQL in the javascript? Wouldn't it make more sense to have a API call in Springboot that the js side talks to to get this? Judging by your code fragment you have a node.js project of some sort like this one?
If you are using Springboot, I think you need to create a API that talks to MySQL, so your javascript will call the API (using something like Axios maybe?)

jQuery never returns - callback function never fires

I previously posted this issue on stackoverflow, but I had simplified it so it could be easier to understand and answer : this was a really bad move as I got totally inadequate answers.
I'm trying to program a Discord Javascript bot using NodeJS. The purpose of this bot is to fetch content from DeviantArt, using their OAuth2 client_id/client_secret authentification method.
My problem is that once the jQuery request is sent, it never goes back and the callback function is never called : so I cannot know what failed because the "status" var stays blank.
var jsdom = require("jsdom").jsdom;
var doc = jsdom();
var window = doc.defaultView;
var $ = require('jquery')(window);
var jsonFinal = '';
var token_url = 'https://www.deviantart.com/oauth2/token';
$.get( token_url, { grant_type: 'client_credentials', client_id: 5946, client_secret: 'whatever'} ).done(function( data ) {
jsonFinal = "("+data.status+data.error+")\n"+data;
console.log(jsonFinal);
});
(I'm using jsdom and jquery on nodeJS 6)
I followed the DA API documentation and I'm pretty sure that these are the right values to send to their server and that this is the right way to send them.
However, the console.log() in this code is never triggered.
How ? Why ?
Your problem is probably that you shouldn't put a function as an argument in your done function. But just in case there is some other problem try this:
var jsdom = require("jsdom").jsdom;
var doc = jsdom();
var window = doc.defaultView;
var $ = require('jquery')(window);
var jsonFinal = '';
var token_url = 'https://www.deviantart.com/oauth2/token';
$.get( token_url, {
grant_type: 'client_credentials',
client_id: 5946,
client_secret: 'whatever'
})
.done(function(data) {
console.log(data);
jsonFinal = "("+data.status+data.error+")\n"+data;
console.log(jsonFinal);
})
.fail(function(error) {
console.log(error);
})
.always(function() {
console.log("done");
});

ASN1 Object's schema was not verified against input data for CERT

Hi I've adapted the HTML certificate parser code to use nodejs from here:
https://github.com/GlobalSign/PKI.js/blob/master/examples/certificate-decode-example.html
However, I keep getting Error: Object's schema was not verified against input data for CERT
Obviously, theres a schema verification issue thats seems to be specific to node JS.
Am I missing something here ?
var merge = require("node.extend");
var common = require("asn1js/org/pkijs/common");
var _asn1js = require("asn1js");
var _pkijs = require("pkijs");
var _x509schema = require("pkijs/org/pkijs/x509_schema");
// #region Merging function/object declarations for ASN1js and PKIjs
var asn1js = merge(true, _asn1js, common);
var x509schema = merge(true, _x509schema, asn1js);
var pkijs_1 = merge(true, _pkijs, asn1js);
var pkijs = merge(true, pkijs_1, x509schema);
certb = `
MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQE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eRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME
HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==
`;
var asn1 = pkijs.org.pkijs.fromBER(certb);
var cert_simpl = new pkijs.org.pkijs.simpl.CERT({ schema: asn1.result });

Apps script write to Big Query unknown error

This is supposed to read in a CSV and then write it to bigquery. When it runs, however, nothing is written, and there are no errors logged. I read that I need to write a csv and then turn it into an Octet Stream. I am not sure whether or not this is compatible with google bigquery.
function test(){
try{
var tableReference = BigQuery.newTableReference();
tableReference.setProjectId(PROJECT_ID);
tableReference.setDatasetId(datasetId);
tableReference.setTableId(tableId);
var schema = "CUSTOMER:string, CLASSNUM:integer, CLASSDESC:string, CSR:string, CSR2:string, INSURANCE:string, REFERRALGENERAL:string, REFERRALSPECIFIC:string, NOTES:string, INMIN:integer, INHR:integer, OUTMIN:integer, OUTHR:integer, WAITMIN:integer, WAITHR:integer, DATETIMESTAMP:float, DATEYR:integer,DATEMONTH:integer, DATEDAY:integer";
var load = BigQuery.newJobConfigurationLoad();
load.setDestinationTable(tableReference);
load.setSourceUris(URIs);
load.setSourceFormat('NEWLINE_DELIMITED_JSON');
load.setSchema(schema);
load.setMaxBadRecords(0);
load.setWriteDisposition('WRITE_TRUNCATE');
var configuration = BigQuery.newJobConfiguration();
configuration.setLoad(load);
var newJob = BigQuery.newJob();
newJob.setConfiguration(configuration);
var loadr = DriveApp.getFilesByName("test.csv");
var x = loadr.next().getBlob();
Logger.log(x.getDataAsString());
var d = DriveApp.getFilesByName("test.csv");
var id = d.next().getId();
Logger.log(id);
var data = DocsList.getFileById(id).getBlob().getDataAsString();
var mediaData = Utilities.newBlob(data, 'application/octet-stream');
BigQuery.Jobs.insert(newJob, PROJECT_ID, mediaData)
}
catch(error){Logger.log("A" + error.message);}
}
Your sourceFormat is wrong for CSV files:
The format of the data files. For CSV files, specify "CSV". For
datastore backups, specify "DATASTORE_BACKUP". For newline-delimited
JSON, specify "NEWLINE_DELIMITED_JSON". The default value is CSV.
https://developers.google.com/bigquery/docs/reference/v2/jobs#configuration.load.sourceUris
On the other hand I think you don't need at all the load.setSourceUris(URIs); since you try to load from local file, and not from Google Cloud Storage. Check this python example https://developers.google.com/bigquery/loading-data-into-bigquery

include external .js file in node.js app

I have an app.js node application. As this file is starting to grow, I would like to move some part of the code in some other files that I would "require" or "include" in the app.js file.
I'm trying things like:
// Declare application
var app = require('express').createServer();
// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
// THE FOLLOWING REQUIRE DOES NOT WORK
require('./models/car.js');
in car.js:
// Define Car model
CarSchema = new Schema({
brand : String,
type : String
});
mongoose.model('Car', CarSchema);
I got the error:
ReferenceError: Schema is not defined
I'm just looking to have the content of car.js loaded (instead of having everything in the same app.js file) Is there a particuliar way to do this in node.js ?
To place an emphasis on what everyone else has been saying var foo in top level does not create a global variable. If you want a global variable then write global.foo. but we all know globals are evil.
If you are someone who uses globals like that in a node.js project I was on I would refactor them away for as there are just so few use cases for this (There are a few exceptions but this isn't one).
// Declare application
var app = require('express').createServer();
// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
require('./models/car.js').make(Schema, mongoose);
in car.js
function make(Schema, mongoose) {
// Define Car model
CarSchema = new Schema({
brand : String,
type : String
});
mongoose.model('Car', CarSchema);
}
module.exports.make = make;
The correct answer is usually to use require, but in a few cases it's not possible.
The following code will do the trick, but use it with care:
var fs = require('fs');
var vm = require('vm');
var includeInThisContext = function(path) {
var code = fs.readFileSync(path);
vm.runInThisContext(code, path);
}.bind(this);
includeInThisContext(__dirname+"/models/car.js");
Short answer:
// lib.js
module.exports.your_function = function () {
// Something...
};
// app.js
require('./lib.js').your_function();
you can put
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
at the top of your car.js file for it to work, or you can do what Raynos said to do.
If you just want to test a library from the command line, you could do:
cat somelibrary.js mytestfile.js | node
This approach works for me in Node.js, Is there any problem with this one?
File 'include.js':
fs = require('fs');
File 'main.js':
require('./include.js');
fs.readFile('./file.json', function (err, data) {
if (err) {
console.log('ERROR: file.json not found...')
} else {
contents = JSON.parse(data)
};
})

Categories

Resources