Cypress 10 and connecting to an Oracle database - database

So I've got a new Cypress 10 project, and I'm trying to integrate some functionality to allow me to make some basic database calls to our Oracle database (which is on a server I have direct access to, not running locally).
I've been following this guide which shows how to add the oracledb package as a Cypress plugin, but the method used (using the /plugin directory) has been depreciated in Cypress 10 so I can't follow the example exactly.
I've instead tried applying this logic using the Cypress plugin documentation as a guide and I think I have something that almost works, but I can't seem to connect to any database, even if the location is in my tnsnames.ora file (although I'm providing the connection string directly for this particular project).
Here's what my cypress.config.ts file looks like, with the code I've created (I'm using Cucumber in my implementation too, thus why those references are present here):
import { defineConfig } from "cypress";
import createBundler from "#bahmutov/cypress-esbuild-preprocessor";
import { addCucumberPreprocessorPlugin } from "#badeball/cypress-cucumber-preprocessor";
import createEsbuildPlugin from "#badeball/cypress-cucumber-preprocessor/esbuild";
const oracledb = require("oracledb");
oracledb.initOracleClient({ libDir: "C:\\Users\\davethepunkyone\\instantclient_21_6" });
// This data is correct, I've obscured it for obvious reasons
const db_config = {
"user": "<username>",
"password": "<password>",
"connectString": "jdbc:oracle:thin:#<hostname>:<port>:<sid>"
}
const queryData = async(query, dbconfig) => {
let conn;
try{
// It's failing on this getConnection line
conn = await oracledb.getConnection(dbconfig);
console.log("NOTE===>connect established")
return await conn.execute(query);
}catch(err){
console.log("Error===>"+err)
return err
} finally{
if(conn){
try{
conn.close();
}catch(err){
console.log("Error===>"+err)
}
}
}
}
async function setupNodeEvents(
on: Cypress.PluginEvents, config: Cypress.PluginConfigOptions ): Promise<Cypress.PluginConfigOptions> {
await addCucumberPreprocessorPlugin(on, config);
on("file:preprocessor", createBundler({
plugins: [createEsbuildPlugin(config)],
})
);
on("task", {
sqlQuery: (query) => {
return queryData(query, db_config);
},
});
return config;
}
export default defineConfig({
e2e: {
specPattern: "**/*.feature",
supportFile: false,
setupNodeEvents,
},
});
I've then got some Cucumber code to run a test query:
Then("I do a test database call", () => {
// Again this is an example query for obvious reasons
const query = "SELECT id FROM table_name FETCH NEXT 1 ROWS ONLY"
cy.task("sqlQuery", query).then((resolvedValue: any) => {
resolvedValue["rows"].forEach((item: any) => {
console.log("result==>" + item);
});
})
})
And here are the dependencies from my package.json:
"dependencies": {
"#badeball/cypress-cucumber-preprocessor": "^12.0.0",
"#bahmutov/cypress-esbuild-preprocessor": "^2.1.3",
"cypress": "^10.4.0",
"oracledb": "^5.4.0",
"typescript": "^4.7.4"
},
I feel like I'm somewhat on the right track as when I run the feature step above, the error I get back is:
Error===>Error: ORA-12154: TNS:could not resolve the connect identifier specified
This makes me think that it has at least called the node-oracledb package to generate the error but I can't really tell if I've made an obvious error or not (I'm pretty new to JS/TS). I know I've referenced the right path for the oracle instant client and it's been initialized correctly at least because Cypress points out a config error if the path is incorrect. I know the database paths work as well because we have an older Selenium implementation that can connect using the details I'm providing.
I think I'm just more curious to know if anyone has so far successfully implemented an oracledb connection with Cypress 10 or if someone who has a bit more Cypress experience can spot any obvious errors in my code as resources for this particular combination of packages seem to be non-existent (possibly because Cypress 10 is reasonably new).
NOTE: I am planning on switching to using environmental variables for the database connection information that will eventually be passed into the project - I just want to get a connection working first before I tackle that issue.

Oracle's C stack drivers like node-oracledb are not using Java so the JDBC connection string needs changing from:
"connectString": "jdbc:oracle:thin:#<hostname>:<port>:<sid>"
If you were using:
jdbc:oracle:thin:#mydbmachine.example.com:1521/orclpdb1
then your Node.js code should use:
connectString : "mydbmachine.example.com:1521/orclpdb1"
Since you're using the very obsolete SID syntax, check the node-oracledb manual for the solution if you can't use a service name: JDBC and Oracle SQL Developer Connection Strings.

Related

react native version check package make app crash

I have installed react-native-version-check by yarn into my project when I use some functions the app crash sending me this message:
WARN [TypeError: Network request failed]
this only happens when I'm using these functions only:
VersionCheck.getLatestVersion()
VersionCheck.needUpdate()
The same thing happens using react-native-check-version package function
There has been some unresolved issues regarding this package and especially those functions that you mentioned. I had faced the same issue previously, my suggestion would be to go with a backend driven version check. You can maintain a table to store the latest version, force update flag, etc. Also since these 2 functions are promise, you can check what they are returning.
VersionCheck.getLatestVersion({
forceUpdate: true,
provider: () => fetch('http://your.own/api')
.then(r => r.json())
.then(({version}) => version), // You can get latest version from your own api.
}).then(latestVersion =>{
console.log(latestVersion);
});
VersionCheck.needUpdate()
.then(async res => {
console.log(res.isNeeded); // true
if (res.isNeeded) {
Linking.openURL(res.storeUrl); // open store if update is needed.
}
});
After some search in the library to know what was making this error
it was actually the fetch API
I had to put these lines of code in my build.gradle
dependencies {
api(platform("com.squareup.okhttp3:okhttp-bom:4.7.2"))
api("com.squareup.okhttp3:okhttp")
api("com.squareup.okhttp3:logging-interceptor")
}
after adding those lines everything worked just fine
version "react-native-version-check": "^3.4.3", is up to date
documentation link:
https://www.npmjs.com/package/react-native-version-check?activeTab=versions

React -- getting ".map is not a function" on PRODUCTION build, but not on regular dev build?

I can't seem to debug this... not sure what's wrong.
This is a React front-end communicating using AXIOS to a Java/MySQL backend. Axios is making CRUD requests over localhost to fetch/update data.
When I run NPM START (development - port 3000) for my React application, it runs fine. However, when I run NPM RUN BUILD and then serve the production build (port 5000), I am getting the following error messages in the console:
Uncaught (in promise) TypeError: this.state.reportData.map is not a function
at t.value (TotalsPerCustomer.js:378)
at Oi (react-dom.production.min.js:3785)
at Ni (react-dom.production.min.js:3776)
at Ri (react-dom.production.min.js:3960)
at Va (react-dom.production.min.js:5514)
at Qa (react-dom.production.min.js:5536)
at Ou (react-dom.production.min.js:5958)
at Pu (react-dom.production.min.js:5925)
at ku (react-dom.production.min.js:5860)
at Ja (react-dom.production.min.js:5787)
I faced this ".map is not a function" previously when I wasn't properly using an ARRAY - but I know this isn't causing the issue now since it works fine on development (Port 3000).
I've tried to do some research on why this is occurring but haven't found any clear answers.
I have added "localhost:5000" to the allowed Origins for CORS in Java back end:
package com.example.groupproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#SpringBootApplication
public class GroupProjectApplication {
public static void main(String[] args) {
SpringApplication.run(GroupProjectApplication.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000","http://localhost:3001","http://localhost:5000");
}
};
}
}
I think I need to understand better what is occurring when a production build is created - I know it creates an minified version of the code -- does this mean that if I have functions named the same thing in different React components then it will create an issue?
Do I need to add the axios dependency somewhere in my WebPack folder? Or is there a different dependency or something missing in my WebPack?
See below screenshot of the console:
I don't really know how to begin debugging using these console errors - can someone shed some light on this?
My apologies for being a little clueless on this production build - any help is much appreciated.
Thanks!
This happen to me as well. First I tried to resolve as it is problem with Array and then finally realized that in reality it is not - because front end (port 5000, production build) lost connection with back end (port 8080) when building for production, hence array was empty.
So this is how I resolved it:
created .env file in root of my React project:
REACT_APP_API_URL_PROD=http://xxx.xxx.xxx.xxx:8080
REACT_APP_API_URL_TEST=http://xxx.xxx.xxx.xxx:8080
REACT_APP_API_URL_DEV=http://localhost:8080
and then in requests.js file (code snippet)
import axios from 'axios';
import endpoints from './endpoints';
if (process.env.NODE_ENV === 'production') {
axios.defaults.baseURL = process.env.REACT_APP_API_URL_PROD;
} else if (process.env.NODE_ENV === 'test') {
axios.defaults.baseURL = process.env.REACT_APP_API_URL_TEST;
} else {
axios.defaults.baseURL = process.env.REACT_APP_API_URL_DEV;
}
export const getRequest = async url => axios.get(url);
export const get = (type, params, options = null) => dispatch => {
const fn = endpoints[type];
axios.defaults.headers.common = {'Authorization': `Bearer ${localStorage.getItem('token')}`};
axios.get(fn(params), options)
.then(response => {
dispatch({
type: type,
payload: response.data
});
});
};
Now, why this is late answer for you, might happen to someone in the future to lose few hours trying to resolve this.
After this, static pages were properly served with 'serve -s build' as well as with Apache HTTP server, and I guess it could be served with any other server.
Please read this for further info.
marked as duplicate of this question:
data.map is not a function
In general, when getting ".map is not a function", this means that you aren't giving an array to map. Only array types can be mapped. So if needed, set the initial state as an empty array (then fetch data, set state, etc.). Bear in mind that if you are mapping certain keys into your page, you may need to set the initial empty array with a 'blank' object, with empty or null values for those keys.
Thanks to those who helped answer this question initially.

MEAN stack not loading page when looking at mongodb collection

I'm having a play with the MEAN stack in order to teach myself a bit of javascript, and use Angular, and i'm having trouble setting up a MEAN environment.
I'm trying to connect to my Mongodb database, and read the contents of the "users" collection, which should contain two records, "John Doe", and "Jane Doe".
This is what my connection string looks like, as well as the constants I have at the top of the api.js
//Importing express, Router, Mongoclient and ObjectID
const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
//Connect
const connection = (closure) => {
//Connecting to "mongod://localhost" line, "/mean" is the name of the DB you
//want to connect too
return MongoClient.connect('mongodb://localhost:27017/mean', { useNewUrlParser: true }, (err, client) => {
if (err) return console.log(err);
var db = client.db('mean');
db.collection('users').findOne({}, function (findErr, result) {
if (findErr) throw findErr;
console.log(result.name);
client.close()
});
//closure(db);
});
};
When I run "node server" from the command line, it runs ok with no error:
C:\Users\jack_\OneDrive\Documents\code\mean>node server
Running on localhost:3000
However, when I try and navigate to "localhost:3000/api/users", nothing happens, the page gets stuck loading, and if I go back to the command line, it shows the first entry in "users":
C:\Users\jack_\OneDrive\Documents\code\mean>node server
Running on localhost:3000
John Doe
I can open the "localhost:3000/api" with no problem, and it takes me to the AngularJS landing page just fine.
I've had a read of over stackoverflow questions and found that there may be a problem with the mongodb driver, as they accidently released a beta version onto npm, so i checked my database version and the driver version:
C:\Users\jack_\OneDrive\Documents\code\mean>"C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe" --version
db version v4.0.2
git version: fc1573ba18aee42f97a3bb13b67af7d837826b47
allocator: tcmalloc
modules: none
build environment:
distmod: 2008plus-ssl
distarch: x86_64
target_arch: x86_64
Database version:
C:\Users\jack_\OneDrive\Documents\code\mean>"C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe" --version
MongoDB shell version v4.0.2
git version: fc1573ba18aee42f97a3bb13b67af7d837826b47
allocator: tcmalloc
modules: none
build environment:
distmod: 2008plus-ssl
distarch: x86_64
target_arch: x86_64
Looking at the other stackoverflow answers, because of the version I'm using, MongoClient.connect now returns a client object containing the database object
So I ammended the code with:
MongoClient.connect('mongodb://localhost:27017/mean', { useNewUrlParser: true }
and
var db = client.db('mean');
db.collection('users').findOne({}, function (findErr, result) {
if (findErr) throw findErr;
console.log(result.name);
client.close()
This got rid of my original error, which was "db.collections is not a function", but, according to the tutorial I'm following, I should see the contents of the "users" collection in a web browser, along with some other information, kinda like this:
{"status":200,"data":[{"_id":"598ce66bf7d6d70def3d9f6f","name":"John Doe"}
But, I'm not,
So what have I done wrong? or am I missing something, bearing in mind I was writing this at 3AM, so I more than likely missed something
Thanks in Advance
You can use below code to connect with db and find the data
const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mean";
MongoClient.connect(url, function(err, client) {
if (err) throw err;
var db = client.db("mean");
db.collection("users").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});

Testing in Meteor

I am trying to add tests in Meteor. I added my tests in the folder 'imports'. This is the test file:
import { Meteor } from 'meteor/meteor';
import { chai } from 'meteor/practicalmeteor:chai';
if (Meteor.isClient) {
describe('Client Tasks', () => {
describe('methods', () => {
it('can delete owned task', () => {
Meteor.call('getVideoData', function (error, res) {
if (error) console.log('error', error)
console.log('ok', res);
})
});
});
});
}
I tried to call a method and log the result but I get the following error:
There is no route for the path: /
The result from the console log is:
error {"isClientSafe":true,"error":404,"reason":"Method 'getVideoData' not found","message":"Method 'getVideoData' not found [404]","errorType":"Meteor.Error"}
and
ok undefined
I used Meteor for the back end and React for the front end.
Am I missing something in the test file or is it related to something else?
This is the link to the repo github
The immediate problem you are seeing is "Method 'getVideoData' not found". That is because running meteor test will only load the modules you have specifically imported. It does not eagerly load your project as we are used to when serving meteor in local development mode. You've only imported Meteor and chai into this test so the test knows nothing about any methods you've written in other files in your project.
However, that leads to a more fundamental problem in that meteor test does not run a front end and back end anyways, so methods are not testable as a way to retrieve data from the server when testing the front end. Instead, when testing the front end you need to stub/mock the call to Meteor.call('getVideoData') and all you can really do is assert that it's been called and supply your own fake return data, as shown in this example.
Then you would need to write separate backend tests to verify the method (and hopefully the compartmentalized functions it calls) are properly retrieving the correct data.

Saving features to SQL Server using Openlayers and geoserver

I am using the SQL Server plugin for geoserver (http://docs.geoserver.org/stable/en/user/data/database/sqlserver.html) to show some geometries using WMS. This works fine. I am also able to extract geometries as vectors without much trouble.
Now I need to add the retrieved vector to another layer and save it to a table in the SQL Server database. This is causing some problems.
This is some of the code:
saveStrategy = new OpenLayers.Strategy.Save();
saveStrategy.events.register("success", '', ChangesSuccess);
saveStrategy.events.register("fail", '', ChangesFailed);
function ChangesSuccess(e) {
alert('Done');
}
function ChangesFailed(e) {
alert('Failed');
}
selectionLayer = new OpenLayers.Layer.Vector(
"SelectionLayer",
{
strategies: [new OpenLayers.Strategy.BBOX(), saveStrategy]
, projection: new OpenLayers.Projection("EPSG:25832")
, protocol: new OpenLayers.Protocol.WFS({
version: "1.1.0",
url: "http://someserver.cloudapp.net:8181/geoserver/wfs",
featurePrefix: 'xxxx',
featureType: "xxxxxxxxx",
featureNS: "xxx.xxx/xxx",
geometryName: "xxxxx"
})
, displayInLayerSwitcher: false
});
selectControl.events.register("featureselected", this, function (e) {
var feat = e.feature;
feat.state = OpenLayers.State.INSERT;
selectionLayer.addFeatures([feat]);
saveStrategy.save();
);
When I try to save the newly added feature I get the following exception in the fail event of the save strategy:
"java.lang.AbstractMethodError:org.geotools.jdbc.BasicSQLDialect.encodeGeometryValue(Lcom/vividsolutions/jts/geom/Geometry;ILjava/lang/StringBuffer;)V org.geotools.jdbc.BasicSQLDialect.encodeGeometryValue(Lcom/vividsolutions/jts/geom/Geometry;ILjava/lang/StringBuffer;)V"
I don't know what to try from here, but if someone has encountered this before or has some suggestions on what could be the issue I am more than happy to hear about it.. It is 1:50am here now and are probably not going to bed before this is fixed so all suggestions are more than welcome :)

Resources